from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser
from rest_framework import status
from django.core.paginator import Paginator
from django.utils import timezone
from .models import RepairService, LeasingApplicationService, ParkingSpaceLeasingService, DecorationApplication, \
    WaterDeliveryService, CleaningBookingService, VisitorAppointmentService, Contract, Visitor, Company, \
    DeviceMaintenance, Device, TemporaryParkingService
from assets.models import Vehicle
from finance.models import Bill
from users.models import ParkEmployeeProfile, CompanyEmployeeProfile, User
from assets.models import Unit
from django.db import transaction
import json
from django.utils import timezone
from django.db.models import Q, Count
import qrcode
import base64
from io import BytesIO
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ValidationError
import json
from datetime import datetime, timedelta
from decimal import Decimal
from django.utils.dateparse import parse_date
from users.models import User  # 添加User模型的导入


# 工单优先级判定函数
def determine_task_priority(task):
    """
    根据工单的属性判断其优先级
    返回值: 'high'(高), 'medium'(中), 'low'(低)
    """
    now = timezone.now()

    # 判断工单类型
    if hasattr(task, 'repair_id'):  # 维修工单
        # 检查是否有期望处理时间
        if task.expected_time:
            # 如果期望处理时间已过或在24小时内，则为高优先级
            time_diff = task.expected_time - now
            if time_diff.total_seconds() <= 0 or time_diff.total_seconds() <= 86400:
                return 'high'
            # 如果期望处理时间在1-3天内，则为中优先级
            elif time_diff.total_seconds() <= 259200:
                return 'medium'

        # 根据申请时间判断
        time_elapsed = now - task.application_time
        # 如果申请已超过3天未处理，则为高优先级
        if time_elapsed.days >= 3 and task.status in ['待受理', '已受理']:
            return 'high'
        # 如果申请已超过1天未处理，则为中优先级
        elif time_elapsed.days >= 1 and task.status in ['待受理', '已受理']:
            return 'medium'

    elif hasattr(task, 'booking_id'):  # 保洁工单
        # 检查预约日期
        if task.expected_service_date:
            # 将日期转换为时区感知的datetime对象
            service_date = timezone.make_aware(
                datetime.combine(task.expected_service_date, datetime.min.time())
            )
            # 获取当前日期（不含时间）
            today = timezone.make_aware(
                datetime.combine(now.date(), datetime.min.time())
            )
            
            # 计算天数差
            days_until_service = (service_date - today).days

            # 如果预约日期是今天或明天，则为高优先级
            if days_until_service <= 1:
                return 'high'
            # 如果预约日期是2-3天内，则为中优先级
            elif days_until_service <= 3:
                return 'medium'

    elif hasattr(task, 'service_id'):  # 送水工单
        # 检查期望送达时间
        if task.expected_delivery_time:
            time_diff = task.expected_delivery_time - now
            # 如果期望送达时间已过或在6小时内，则为高优先级
            if time_diff.total_seconds() <= 0 or time_diff.total_seconds() <= 21600:
                return 'high'
            # 如果期望送达时间在6-24小时内，则为中优先级
            elif time_diff.total_seconds() <= 86400:
                return 'medium'

    # 默认为低优先级
    return 'low'


def _get_user_real_name(user: User):
    """
    高效地获取用户的真实姓名，如果档案不存在则返回其用户名。
    依赖于调用方已经对 companyemployeeprofile 和 parkemployeeprofile 进行了 prefetch_related。
    """
    if not user:
        return None
    try:
        # 优先从企业员工档案获取
        return user.companyemployeeprofile.name
    except CompanyEmployeeProfile.DoesNotExist:
        try:
            # 其次从园区员工档案获取
            return user.parkemployeeprofile.name
        except ParkEmployeeProfile.DoesNotExist:
            # 如果都没有，返回用户名
            return user.username
    except AttributeError:
        # 处理 user.companyemployeeprofile/parkemployeeprofile 不存在的情况
        return user.username


def _get_repair_location(obj):
    """
    获取报修位置的详细描述
    """
    if obj.unit:
        return f"{obj.unit.building.name} {obj.unit.floor.actual_label} {obj.unit.unit_number}"
    if obj.device and obj.device.unit:
        return f"单元内设备: {obj.device.unit.building.name} {obj.device.unit.floor.actual_label} {obj.device.unit.unit_number}"
    if obj.device:
        location_parts = [
            obj.device.building.name,
            obj.device.floor.actual_label if obj.device.floor else None,
            obj.device.location_desc
        ]
        return ' '.join(filter(None, location_parts))
    return "园区公共区域"


@api_view(['GET'])
def repair_list(request):
    """
    获取报修服务列表
    """
    params = request.query_params
    page = int(params.get('current', 1))
    size = int(params.get('size', 10))
    ordering = params.get('ordering')

    queryset = RepairService.objects.select_related(
        'applicant_user',
        'handler_user',
        'unit__building',
        'unit__floor',
        'device__building',
        'device__floor',
        'device__unit__building',
        'device__unit__floor'
    ).prefetch_related(
        'applicant_user__companyemployeeprofile',
        'applicant_user__parkemployeeprofile',
        'handler_user__parkemployeeprofile'
    )

    if params.get('status'):
        queryset = queryset.filter(status=params.get('status'))

    if ordering:
        queryset = queryset.order_by(ordering)
    else:
        queryset = queryset.order_by('repair_id')

    paginator = Paginator(queryset, size)
    repairs_page = paginator.get_page(page)

    repairs = []
    for repair in repairs_page:
        # 计算优先级
        priority = determine_task_priority(repair)

        repairs.append({
            'repair_id': repair.repair_id,
            'applicant_user_name': _get_user_real_name(repair.applicant_user),
            'location': _get_repair_location(repair),
            'fault_description': repair.fault_description,
            'application_time': repair.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': repair.status,
            'priority': priority,  # 添加优先级字段
            'handler_user_name': _get_user_real_name(repair.handler_user),
            'completion_time': repair.completion_time.strftime('%Y-%m-%d %H:%M:%S') if repair.completion_time else None,
        })

    return Response({
        'code': 200,
        'message': '获取报修列表成功',
        'data': {
            'total': paginator.count,
            'list': repairs
        }
    })


@api_view(['GET', 'PUT'])
def repair_detail(request, pk):
    """
    获取单个报修详情
    """
    try:
        repair = RepairService.objects.select_related(
            'applicant_user',
            'handler_user',
            'unit__building',
            'unit__floor',
            'device__building',
            'device__floor',
            'device__unit__building',
            'device__unit__floor'
        ).get(repair_id=pk)
    except RepairService.DoesNotExist:
        return Response({'code': 404, 'message': '报修记录不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        media_urls_list = []
        if repair.media_urls:
            try:
                media_urls_list = json.loads(repair.media_urls)
            except json.JSONDecodeError:
                media_urls_list = []

        data = {
            'repair_id': repair.repair_id,
            'applicant_user': {
                'user_id': repair.applicant_user.user_id,
                'username': repair.applicant_user.username,
            },
            'location': _get_repair_location(repair),
            'fault_description': repair.fault_description,
            'media_urls': media_urls_list,
            'expected_time': repair.expected_time.strftime('%Y-%m-%d %H:%M:%S') if repair.expected_time else None,
            'application_time': repair.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': repair.status,
            'handler_user': {
                'user_id': repair.handler_user.user_id,
                'username': repair.handler_user.username,
            } if repair.handler_user else None,
            'completion_time': repair.completion_time.strftime('%Y-%m-%d %H:%M:%S') if repair.completion_time else None,
            'repair_result': repair.repair_result,
            'repair_cost': str(repair.repair_cost) if repair.repair_cost is not None else None,
            'rating': repair.rating,
            'review_content': repair.review_content,
        }
        return Response({'code': 200, 'message': '获取报修详情成功', 'data': data})

    elif request.method == 'PUT':
        handler_user_id = request.data.get('handler_user_id')
        if not handler_user_id:
            return Response({'code': 400, 'message': '必须提供处理人ID'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            repair.handler_user_id = handler_user_id
            repair.status = '处理中'  # Update status upon assignment
            repair.save()
            return Response({'code': 200, 'message': '指派成功'})
        except Exception as e:
            return Response({'code': 500, 'message': f'指派失败: {str(e)}'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def leasing_application_list(request):
    """
    获取租赁申请列表 (包含房源和车位)
    """
    params = request.query_params
    page = int(params.get('current', 1))
    size = int(params.get('size', 10))
    application_type = params.get('application_type')
    status_filter = params.get('status')

    # 查询房源租赁申请
    property_applications = LeasingApplicationService.objects.select_related(
        'applicant_user', 'company', 'unit__building'
    ).prefetch_related(
        'applicant_user__companyemployeeprofile',
        'applicant_user__parkemployeeprofile'
    ).all()

    # 查询车位租赁申请
    parking_applications = ParkingSpaceLeasingService.objects.select_related(
        'applicant_user', 'unit__building', 'vehicle'
    ).prefetch_related(
        'applicant_user__companyemployeeprofile',
        'applicant_user__parkemployeeprofile'
    ).all()

    if status_filter:
        property_applications = property_applications.filter(status=status_filter)
        parking_applications = parking_applications.filter(status=status_filter)

    # 规范化数据并合并
    combined_list = []

    if not application_type or application_type == '房源租赁':
        for app in property_applications:
            combined_list.append({
                'id': f'prop-{app.application_id}',
                'application_type': '房源租赁',
                'applicant': _get_user_real_name(app.applicant_user),
                'company': app.company.company_name if app.company else '-',
                'subject': f"{app.unit.building.name} {app.unit.unit_number}",
                'application_time': app.application_time,
                'status': app.status
            })

    if not application_type or application_type == '车位租赁':
        for app in parking_applications:
            combined_list.append({
                'id': f'park-{app.application_id}',
                'application_type': '车位租赁',
                'applicant': _get_user_real_name(app.applicant_user),
                'company': '-',
                'subject': f"车位: {app.unit.unit_number} (车辆: {app.vehicle.plate_number})",
                'application_time': app.application_time,
                'status': app.status
            })

    # 按申请时间排序
    combined_list.sort(key=lambda x: x['application_time'], reverse=True)

    # 手动分页
    paginator = Paginator(combined_list, size)
    page_obj = paginator.get_page(page)

    # 格式化日期
    for item in page_obj.object_list:
        item['application_time'] = item['application_time'].strftime('%Y-%m-%d %H:%M:%S')

    return Response({
        'code': 200,
        'message': '获取租赁申请列表成功',
        'data': {
            'total': paginator.count,
            'list': page_obj.object_list
        }
    })


@api_view(['GET'])
def leasing_application_detail(request, pk):
    """
    获取单个租赁申请详情 (包含房源和车位)
    pk: 复合主键, e.g., 'prop-1' or 'park-2'
    """
    try:
        app_type, app_id = pk.split('-')
        app_id = int(app_id)
    except (ValueError, IndexError):
        return Response({'code': 400, 'message': '无效的ID格式'}, status=status.HTTP_400_BAD_REQUEST)

    data = {}
    try:
        if app_type == 'prop':
            app = LeasingApplicationService.objects.select_related(
                'applicant_user', 'company', 'unit__building', 'unit__floor'
            ).get(application_id=app_id)

            # 当查看时，如果状态为"待审核"，则自动更新为"审核中"
            if app.status == '待审核':
                app.status = '审核中'
                app.save()

            data = {
                'id': f'prop-{app.application_id}',
                'application_type': '房源租赁',
                'applicant': _get_user_real_name(app.applicant_user),
                'company': app.company.company_name if app.company else '-',
                'unit_info': {
                    'building': app.unit.building.name,
                    'floor': app.unit.floor.actual_label,
                    'number': app.unit.unit_number,
                    'area': str(app.unit.actual_area)
                },
                'expected_start_date': app.expected_start_date.strftime('%Y-%m-%d'),
                'expected_duration': f"{app.expected_duration}个月",
                'application_time': app.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                'status': app.status,
                'approval_opinion': app.approval_opinion
            }
        elif app_type == 'park':
            app = ParkingSpaceLeasingService.objects.select_related(
                'applicant_user', 'unit__building', 'unit__floor', 'vehicle'
            ).get(application_id=app_id)

            # 当查看时，如果状态为"待审核"，则自动更新为"审核中"
            if app.status == '待审核':
                app.status = '审核中'
                app.save()

            data = {
                'id': f'park-{app.application_id}',
                'application_type': '车位租赁',
                'applicant': _get_user_real_name(app.applicant_user),
                'company': '-',
                'unit_info': {
                    'building': app.unit.building.name,
                    'floor': app.unit.floor.actual_label if app.unit.floor else 'N/A',
                    'number': app.unit.unit_number
                },
                'vehicle_info': {
                    'plate_number': app.vehicle.plate_number,
                    'brand': app.vehicle.brand,
                    'model': app.vehicle.model,
                },
                'expected_start_date': app.expected_start_date.strftime('%Y-%m-%d'),
                'expected_duration': f"{app.expected_duration}个月",
                'application_time': app.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                'status': app.status,
                'approval_opinion': app.approval_opinion
            }
        else:
            return Response({'code': 400, 'message': '无效的申请类型'}, status=status.HTTP_400_BAD_REQUEST)

        return Response({'code': 200, 'message': '获取详情成功', 'data': data})

    except (LeasingApplicationService.DoesNotExist, ParkingSpaceLeasingService.DoesNotExist):
        return Response({'code': 404, 'message': '申请记录不存在'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({'code': 500, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
def approve_leasing_application(request, pk):
    """
    审批租赁申请 (通过/驳回)
    """
    try:
        app_type, app_id = pk.split('-')
        app_id = int(app_id)
    except (ValueError, IndexError):
        return Response({'code': 400, 'message': '无效的ID格式'}, status=status.HTTP_400_BAD_REQUEST)

    new_status = request.data.get('status')
    approval_opinion = request.data.get('approval_opinion', '')

    if new_status not in ['审核通过', '审核驳回']:
        return Response({'code': 400, 'message': '无效的状态'}, status=status.HTTP_400_BAD_REQUEST)

    try:
        if app_type == 'prop':
            app = LeasingApplicationService.objects.get(application_id=app_id)
        elif app_type == 'park':
            app = ParkingSpaceLeasingService.objects.get(application_id=app_id)
        else:
            return Response({'code': 400, 'message': '无效的申请类型'}, status=status.HTTP_400_BAD_REQUEST)

        # 增加状态检查，只有"待审核"的申请才能被审批
        if app.status not in ['待审核', '审核中']:
            return Response({'code': 400, 'message': f'申请状态为"{app.status}"，无法审批'},
                            status=status.HTTP_400_BAD_REQUEST)

        app.status = new_status
        app.approval_opinion = approval_opinion
        app.save()

        return Response({'code': 200, 'message': '审批操作成功'})

    except (LeasingApplicationService.DoesNotExist, ParkingSpaceLeasingService.DoesNotExist):
        return Response({'code': 404, 'message': '申请记录不存在'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({'code': 500, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def decoration_application_list(request):
    """
    获取装修备案列表
    """
    params = request.query_params
    page = int(params.get('current', 1))
    size = int(params.get('size', 10))
    status_filter = params.get('status')
    ordering = params.get('ordering')

    queryset = DecorationApplication.objects.select_related(
        'applicant_user', 'unit__building', 'unit__floor'
    ).prefetch_related(
        'applicant_user__companyemployeeprofile',
        'applicant_user__parkemployeeprofile'
    )

    if status_filter:
        queryset = queryset.filter(status=status_filter)

    if ordering:
        queryset = queryset.order_by(ordering)
    else:
        queryset = queryset.order_by('application_id')

    paginator = Paginator(queryset, size)
    page_obj = paginator.get_page(page)

    application_list = []
    for app in page_obj.object_list:
        application_list.append({
            'application_id': app.application_id,
            'applicant_name': _get_user_real_name(app.applicant_user),
            'unit_info': f"{app.unit.building.name} {app.unit.unit_number}",
            'construction_company': app.construction_company,
            'application_date': app.application_date.strftime('%Y-%m-%d'),
            'status': app.status
        })

    return Response({
        'code': 200,
        'message': '获取装修备案列表成功',
        'data': {
            'total': paginator.count,
            'list': application_list
        }
    })


@api_view(['GET'])
def decoration_application_detail(request, pk):
    """
    获取单个装修备案详情
    """
    try:
        app = DecorationApplication.objects.select_related(
            'applicant_user', 'unit__building', 'unit__floor'
        ).get(application_id=pk)
    except DecorationApplication.DoesNotExist:
        return Response({'code': 404, 'message': '申请记录不存在'}, status=status.HTTP_404_NOT_FOUND)

    # 当查看时，如果状态为"待审核"，则自动更新为"审核中"
    if app.status == '待审核':
        app.status = '审核中'
        app.save()

    design_plan_urls = []
    if app.design_plan_url:
        try:
            design_plan_urls = json.loads(app.design_plan_url)
        except json.JSONDecodeError:
            design_plan_urls = []

    construction_staff = []
    if app.construction_staff_info:
        try:
            construction_staff = json.loads(app.construction_staff_info)
        except json.JSONDecodeError:
            construction_staff = []

    data = {
        'application_id': app.application_id,
        'applicant_name': _get_user_real_name(app.applicant_user),
        'unit_info_str': f"{app.unit.building.name} {app.unit.floor.actual_label} {app.unit.unit_number}",
        'unit_info': {
            'building': app.unit.building.name,
            'floor': app.unit.floor.actual_label,
            'number': app.unit.unit_number,
            'area': str(app.unit.actual_area)
        },
        'application_date': app.application_date.strftime('%Y-%m-%d'),
        'design_plan_url': design_plan_urls,
        'construction_company': app.construction_company,
        'construction_staff_info': construction_staff,
        'estimated_duration': app.estimated_duration,
        'status': app.status,
        'approval_opinion': app.approval_opinion,
    }
    return Response({'code': 200, 'message': '获取详情成功', 'data': data})


@api_view(['PUT'])
def approve_decoration_application(request, pk):
    """
    审批装修备案申请 (通过/驳回)
    """
    new_status = request.data.get('status')
    approval_opinion = request.data.get('approval_opinion', '')

    if new_status not in ['审核通过', '审核驳回']:
        return Response({'code': 400, 'message': '无效的状态'}, status=status.HTTP_400_BAD_REQUEST)

    try:
        app = DecorationApplication.objects.get(application_id=pk)

        if app.status not in ['待审核', '审核中']:
            return Response({'code': 400, 'message': f'申请状态为"{app.status}"，无法审批'},
                            status=status.HTTP_400_BAD_REQUEST)

        app.status = new_status
        app.approval_opinion = approval_opinion
        app.save()

        return Response({'code': 200, 'message': '审批操作成功'})
    except DecorationApplication.DoesNotExist:
        return Response({'code': 404, 'message': '申请记录不存在'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({'code': 500, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def water_delivery_list(request):
    """
    获取送水服务列表
    """
    params = request.query_params
    page = int(params.get('page') or params.get('current') or 1)
    size = int(params.get('pageSize') or params.get('size') or 10)
    status_filter = params.get('status')
    keyword = params.get('keyword')
    contact_phone = params.get('contact_phone')

    queryset = WaterDeliveryService.objects.select_related(
        'applicant_user', 'deliverer_user', 'unit'
    ).prefetch_related(
        'applicant_user__companyemployeeprofile',
        'applicant_user__parkemployeeprofile',
        'deliverer_user__parkemployeeprofile'
    ).order_by('-application_time')

    if status_filter:
        # 支持多状态查询，例如 "已受理,服务中"
        if ',' in status_filter:
            statuses = [s.strip() for s in status_filter.split(',')]
            queryset = queryset.filter(status__in=statuses)
        else:
            queryset = queryset.filter(status=status_filter)

    if keyword:
        # 支持通过工单ID或产品名称搜索
        queryset = queryset.filter(
            Q(service_id__icontains=keyword) |
            Q(product_name__icontains=keyword)
        )

    if contact_phone:
        queryset = queryset.filter(contact_phone__icontains=contact_phone)

    if params.get('start_date'):
        queryset = queryset.filter(application_time__gte=params.get('start_date'))
    if params.get('end_date'):
        # 包含结束当天
        end_date_d = datetime.strptime(params.get('end_date'), '%Y-%m-%d').date()
        queryset = queryset.filter(application_time__date__lte=end_date_d)

    paginator = Paginator(queryset, size)
    page_obj = paginator.get_page(page)

    service_list = []
    for service in page_obj.object_list:
        priority_code = determine_task_priority(service)
        # 将优先级代码转换为中文显示
        priority_map = {
            'high': '高',
            'medium': '中',
            'low': '低'
        }
        priority = priority_map.get(priority_code, '低')

        service_list.append({
            'id': service.service_id,
            'applicant_user_info': {
                'name': _get_user_real_name(service.applicant_user)} if service.applicant_user else None,
            'deliverer_user_info': {
                'name': _get_user_real_name(service.deliverer_user)} if service.deliverer_user else None,
            'unit_info': {'unit_number': service.unit.unit_number} if service.unit else None,
            'contact_name': service.contact_name,
            'contact_phone': service.contact_phone,
            'delivery_address': service.delivery_address,
            'product_name': service.product_name,
            'quantity': service.quantity,
            'application_time': service.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'expected_delivery_time': service.expected_delivery_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': service.status,
            'priority': priority,
        })

    return Response({
        'code': 200,
        'message': '获取送水服务列表成功',
        'data': {
            'total': paginator.count,
            'list': service_list
        }
    })


@api_view(['GET', 'PUT'])
def water_delivery_detail(request, pk):
    """
    获取、更新单个送水服务的详情。
    主要用于管理员指派配送员。
    """
    try:
        service = WaterDeliveryService.objects.select_related(
            'applicant_user', 'deliverer_user', 'unit'
        ).get(service_id=pk)
    except WaterDeliveryService.DoesNotExist:
        return Response({'code': 404, 'message': '服务记录不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        data = {
            'service_id': service.service_id,
            'applicant_user_info': {
                'name': _get_user_real_name(service.applicant_user)} if service.applicant_user else None,
            'unit_info': {'unit_id': service.unit.unit_id,
                          'unit_number': service.unit.unit_number} if service.unit else None,
            'product_name': service.product_name,
            'quantity': service.quantity,
            'unit_price': str(service.unit_price),
            'total_amount': str(service.total_amount),
            'expected_delivery_time': service.expected_delivery_time.strftime('%Y-%m-%d %H:%M:%S'),
            'delivery_address': service.delivery_address,
            'contact_name': service.contact_name,
            'contact_phone': service.contact_phone,
            'application_time': service.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': service.status,
            'deliverer_user_info': {
                'name': _get_user_real_name(service.deliverer_user)} if service.deliverer_user else None,
            'actual_delivery_time': service.actual_delivery_time.strftime(
                '%Y-%m-%d %H:%M:%S') if service.actual_delivery_time else None,
            'rating': service.rating,
            'review_content': service.review_content,
        }
        return Response({'code': 200, 'message': '获取详情成功', 'data': data})

    elif request.method == 'PUT':
        deliverer_user_id = request.data.get('deliverer_user_id')
        if not deliverer_user_id:
            return Response({'code': 400, 'message': '必须提供配送员ID'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            deliverer = User.objects.get(pk=deliverer_user_id)
            service.deliverer_user = deliverer
            if service.status == '待受理':
                service.status = '配送中'
            service.save()
            return Response({'code': 200, 'message': '指派成功'})
        except User.DoesNotExist:
            return Response({'code': 404, 'message': '指定的配送员不存在'}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({'code': 500, 'message': f'指派失败: {str(e)}'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def cleaning_booking_list(request):
    """
    获取保洁预约服务列表
    """
    params = request.query_params
    page = int(params.get('current', 1))
    size = int(params.get('size', 10))
    status_filter = params.get('status')
    user_only = params.get('user_only') == 'true'

    queryset = CleaningBookingService.objects.select_related(
        'applicant_user', 'handler_user', 'unit__building', 'unit__floor'
    ).prefetch_related(
        'applicant_user__companyemployeeprofile',
        'applicant_user__parkemployeeprofile',
        'handler_user__parkemployeeprofile'
    ).order_by('-application_time')

    if status_filter:
        queryset = queryset.filter(status=status_filter)

    # 如果指定了user_only参数，则只返回当前用户的记录
    if user_only and request.user and request.user.is_authenticated:
        queryset = queryset.filter(applicant_user=request.user)

    paginator = Paginator(queryset, size)
    page_obj = paginator.get_page(page)

    booking_list = []
    for booking in page_obj.object_list:
        booking_list.append({
            'booking_id': booking.booking_id,
            'applicant_user_info': {
                'name': _get_user_real_name(booking.applicant_user)} if booking.applicant_user else None,
            'unit_info': f"{booking.unit.building.name} {booking.unit.floor.actual_label} {booking.unit.unit_number}" if booking.unit else 'N/A',
            'expected_service_date': booking.expected_service_date.strftime('%Y-%m-%d'),
            'expected_time_slot': booking.expected_time_slot,
            'application_time': booking.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': booking.status,
            'handler_user_info': {'name': _get_user_real_name(booking.handler_user)} if booking.handler_user else None,
        })

    return Response({
        'code': 200,
        'message': '获取保洁预约列表成功',
        'data': {
            'total': paginator.count,
            'list': booking_list
        }
    })


@api_view(['GET', 'PUT'])
def cleaning_booking_detail(request, pk):
    """
    获取、更新单个保洁预约的详情。
    主要用于管理员指派保洁员。
    """
    try:
        booking = CleaningBookingService.objects.select_related(
            'applicant_user', 'handler_user', 'unit'
        ).get(booking_id=pk)
    except CleaningBookingService.DoesNotExist:
        return Response({'code': 404, 'message': '预约记录不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        data = {
            'booking_id': booking.booking_id,
            'applicant_user_info': {
                'name': _get_user_real_name(booking.applicant_user)} if booking.applicant_user else None,
            'unit_info_str': f"{booking.unit.building.name} {booking.unit.floor.actual_label} {booking.unit.unit_number}" if booking.unit else 'N/A',
            'expected_service_date': booking.expected_service_date.strftime('%Y-%m-%d'),
            'expected_time_slot': booking.expected_time_slot,
            'special_requirements': booking.special_requirements,
            'application_time': booking.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': booking.status,
            'handler_user_info': {'name': _get_user_real_name(booking.handler_user)} if booking.handler_user else None,
            'completion_time': booking.completion_time.strftime(
                '%Y-%m-%d %H:%M:%S') if booking.completion_time else None,
            'service_fee': str(booking.service_fee) if booking.service_fee is not None else None,
            'rating': booking.rating,
            'review_content': booking.review_content,
        }
        return Response({'code': 200, 'message': '获取详情成功', 'data': data})

    elif request.method == 'PUT':
        handler_user_id = request.data.get('handler_user_id')
        if not handler_user_id:
            return Response({'code': 400, 'message': '必须提供处理人ID'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            handler = User.objects.get(pk=handler_user_id)
            booking.handler_user = handler
            if booking.status == '待受理':
                booking.status = '服务中'
            booking.save()
            return Response({'code': 200, 'message': '指派成功'})
        except User.DoesNotExist:
            return Response({'code': 404, 'message': '指定的处理人不存在'}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({'code': 500, 'message': f'指派失败: {str(e)}'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 公共工具函数
def parse_date(date_str, format='%Y-%m-%d'):
    """安全解析日期字符串"""
    try:
        return datetime.strptime(date_str, format).date()
    except (ValueError, TypeError):
        return None


def validate_required_fields(data, required_fields):
    """验证必填字段"""
    missing_fields = [field for field in required_fields if field not in data or not data[field]]
    if missing_fields:
        raise ValidationError(f"缺少必填字段: {', '.join(missing_fields)}")


# 保洁预约服务


# views.py
@csrf_exempt
def create_cleaning_booking(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)

            # 获取或验证Unit实例
            try:
                unit_instance = Unit.objects.get(unit_id=int(data['unit_id']))
            except Unit.DoesNotExist:
                return JsonResponse({
                    'status': 'error',
                    'message': '指定的单元不存在'
                }, status=400)
            except (ValueError, KeyError):
                return JsonResponse({
                    'status': 'error',
                    'message': '无效的单元ID格式'
                }, status=400)

            # 获取用户实例
            try:
                applicant_user_id = data.get('applicant_user_id')
                if not applicant_user_id:
                    return JsonResponse({
                        'status': 'error',
                        'message': '申请用户ID不能为空'
                    }, status=400)

                user_instance = User.objects.get(user_id=int(applicant_user_id))
            except User.DoesNotExist:
                return JsonResponse({
                    'status': 'error',
                    'message': '指定的用户不存在'
                }, status=400)
            except (ValueError, KeyError):
                return JsonResponse({
                    'status': 'error',
                    'message': '无效的用户ID格式'
                }, status=400)

            # 创建记录
            now = datetime.now()
            booking = CleaningBookingService(
                unit=unit_instance,  # 使用模型实例
                applicant_user=user_instance,  # 添加申请用户
                expected_service_date=data['expected_service_date'],
                expected_time_slot=data['expected_time_slot'],
                special_requirements=data.get('special_requirements', ''),
                application_time=now,  # 添加申请时间
                status='待受理',  # 修改为中文状态，与其他服务保持一致
                created_at=now,
                updated_at=now
            )
            booking.save()

            return JsonResponse({'status': 'success', 'message': '预约成功'})

        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'message': f'数据库操作失败: {str(e)}'
            }, status=500)


@api_view(['GET', 'POST'])
@permission_classes([AllowAny])
def visitor_appointment_list(request):
    """
    获取访客预约列表或创建新预约
    """
    if request.method == 'GET':
        params = request.query_params
        page = int(params.get('page', 1))
        page_size = int(params.get('pageSize', 10))

        queryset = VisitorAppointmentService.objects.select_related(
            'visitor', 'visited_company', 'inviter_user'
        ).order_by('-expected_visit_time')

        # 筛选
        if params.get('visitor_name'):
            queryset = queryset.filter(visitor__name__icontains=params.get('visitor_name'))
        if params.get('visitor_phone'):
            queryset = queryset.filter(visitor__phone__icontains=params.get('visitor_phone'))
        if params.get('status') and params.get('status') != '':
            status_map = {'0': '待审批', '1': '已批准', '2': '已拒绝', '3': '已入园', '4': '已离园', '5': '已取消'}
            status_str = status_map.get(params.get('status'))
            if status_str:
                queryset = queryset.filter(status=status_str)

        if params.get('start_date'):
            start_date = datetime.datetime.strptime(params.get('start_date'), '%Y-%m-%d').date()
            aware_start_datetime = timezone.make_aware(datetime.datetime.combine(start_date, datetime.time.min))
            queryset = queryset.filter(expected_visit_time__gte=aware_start_datetime)
        if params.get('end_date'):
            end_date = datetime.datetime.strptime(params.get('end_date'), '%Y-%m-%d').date()
            aware_end_datetime = timezone.make_aware(datetime.datetime.combine(end_date, datetime.time.max))
            queryset = queryset.filter(expected_visit_time__lte=aware_end_datetime)

        paginator = Paginator(queryset, page_size)
        page_obj = paginator.get_page(page)

        appointment_list = []
        status_map_rev = {'待审批': 0, '已批准': 1, '已拒绝': 2, '已入园': 3, '已离园': 4, '已取消': 5}

        for app in page_obj.object_list:
            appointment_list.append({
                'appointment_id': app.appointment_id,
                'visitor': {
                    'visitor_id': app.visitor.visitor_id,
                    'name': app.visitor.name,
                    'phone': app.visitor.phone,
                    'id_card': app.visitor.id_card
                },
                'visited_company': {
                    'company_id': app.visited_company.company_id,
                    'company_name': app.visited_company.company_name
                } if app.visited_company else None,
                'visit_purpose': app.visit_purpose,
                'expected_visit_time': app.expected_visit_time.isoformat(),
                'status': status_map_rev.get(app.status, -1),
                'created_at': app.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })

        return Response({
            'code': 200,
            'message': '获取访客预约列表成功',
            'data': {
                'total': paginator.count,
                'list': appointment_list
            }
        })

    elif request.method == 'POST':
        data = request.data
        visitor_id = data.get('visitor_id')

        if not visitor_id:
            return Response({'code': 400, 'message': '缺少访客ID'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            with transaction.atomic():
                try:
                    visitor = Visitor.objects.get(visitor_id=visitor_id)
                except Visitor.DoesNotExist:
                    return Response({'code': 404, 'message': '指定的访客不存在'}, status=status.HTTP_404_NOT_FOUND)

                # 获取邀请人用户，优先使用传入的inviter_user_id
                inviter_user = None
                inviter_user_id = data.get('inviter_user_id')

                if inviter_user_id:
                    try:
                        inviter_user = User.objects.get(user_id=inviter_user_id)
                    except User.DoesNotExist:
                        # 如果指定的用户不存在，使用默认策略
                        pass

                # 如果没有有效的邀请人ID，尝试使用默认策略
                if not inviter_user:
                    # 尝试从企业员工中随机选择一个
                    company_employee = CompanyEmployeeProfile.objects.order_by('?').first()
                    if company_employee:
                        inviter_user = company_employee.user
                    else:
                        # 如果没有企业员工，返回错误
                        return Response({'code': 400, 'message': '无法确定邀请人，请提供有效的邀请人ID'},
                                        status=status.HTTP_400_BAD_REQUEST)

                visited_company = Company.objects.get(pk=data['visited_company_id']) if data.get(
                    'visited_company_id') else None

                status_map = {0: '待审批', 1: '已批准', 2: '已拒绝', 3: '已入园', 4: '已离园', 5: '已取消'}

                appointment = VisitorAppointmentService.objects.create(
                    visitor=visitor,
                    inviter_user=inviter_user,
                    visited_company=visited_company,
                    expected_visit_time=data['expected_visit_time'],
                    visit_purpose=data['visit_purpose'],
                    status=status_map.get(data.get('status', 0), '待审批'),
                    accompanier_info=data.get('accompanier_info', '[]')
                )

            return Response(
                {'code': 201, 'message': '创建成功', 'data': {'appointment_id': appointment.appointment_id}},
                status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'code': 500, 'message': f'创建失败: {str(e)}'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET', 'PUT', 'DELETE'])
def visitor_appointment_detail(request, pk):
    """
    获取、更新或删除单个访客预约
    """
    try:
        appointment = VisitorAppointmentService.objects.select_related('visitor', 'visited_company').get(
            appointment_id=pk)
    except VisitorAppointmentService.DoesNotExist:
        return Response({'code': 404, 'message': '预约记录不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        status_map_rev = {'待审批': 0, '已批准': 1, '已拒绝': 2, '已入园': 3, '已离园': 4, '已取消': 5}
        data = {
            'appointment_id': appointment.appointment_id,
            'visitor': {
                'visitor_id': appointment.visitor.visitor_id,
                'name': appointment.visitor.name,
                'phone': appointment.visitor.phone,
                'id_card': appointment.visitor.id_card
            },
            'visited_company': {
                'company_id': appointment.visited_company.company_id,
                'company_name': appointment.visited_company.company_name
            } if appointment.visited_company else None,
            'visit_purpose': appointment.visit_purpose,
            'expected_visit_time': appointment.expected_visit_time.isoformat(),
            'status': status_map_rev.get(appointment.status, -1),
            'accompanier_info': appointment.accompanier_info
        }
        return Response({'code': 200, 'message': '获取成功', 'data': data})

    elif request.method == 'PUT':
        data = request.data
        status_code = data.get('status')
        status_map = {0: '待审批', 1: '已批准', 2: '已拒绝', 3: '已入园', 4: '已离园', 5: '已取消'}

        # 简化版：只更新状态
        if status_code is not None and status_code in status_map:
            appointment.status = status_map[status_code]
            appointment.save()
            return Response({'code': 200, 'message': '状态更新成功'})

        # 完整更新
        try:
            with transaction.atomic():
                visitor_data = data.get('visitor')
                if visitor_data:
                    visitor = appointment.visitor
                    visitor.name = visitor_data.get('name', visitor.name)
                    visitor.phone = visitor_data.get('phone', visitor.phone)
                    visitor.id_card = visitor_data.get('id_card', visitor.id_card)
                    visitor.save()

                if data.get('visited_company_id'):
                    appointment.visited_company = Company.objects.get(pk=data['visited_company_id'])

                appointment.visit_purpose = data.get('visit_purpose', appointment.visit_purpose)
                appointment.expected_visit_time = data.get('expected_visit_time', appointment.expected_visit_time)
                if status_code is not None:
                    appointment.status = status_map.get(status_code, appointment.status)

                appointment.save()
            return Response({'code': 200, 'message': '更新成功'})
        except Exception as e:
            return Response({'code': 500, 'message': f'更新失败: {str(e)}'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    elif request.method == 'DELETE':
        try:
            appointment.delete()
            return Response({'code': 204, 'message': '删除成功'}, status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            return Response({'code': 500, 'message': f'删除失败: {str(e)}'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def contract_list(request):
    """
    获取合同列表
    """
    params = request.query_params
    page = int(params.get('current', 1))
    size = int(params.get('size', 10))
    status = params.get('status', '')
    tenant_name = params.get('tenantName', '')

    queryset = Contract.objects.select_related(
        'unit__building',
        'company',
        'user'
    ).order_by('-contract_id')

    # 根据状态筛选
    if status:
        queryset = queryset.filter(status=status)
    
    # 根据租户名称筛选
    if tenant_name:
        # 同时从公司和用户中查找匹配的租户
        from django.db.models import Q
        company_contracts = queryset.filter(company__company_name__icontains=tenant_name)
        # 修复用户名称查询，使用正确的字段路径
        user_contracts = queryset.filter(
            Q(user__username__icontains=tenant_name) | 
            Q(user__companyemployeeprofile__name__icontains=tenant_name) | 
            Q(user__parkemployeeprofile__name__icontains=tenant_name)
        )
        queryset = company_contracts | user_contracts

    paginator = Paginator(queryset, size)
    contracts_page = paginator.get_page(page)

    contracts = []
    for contract in contracts_page:
        asset_name = ""
        if contract.unit:
            asset_name = f"{contract.unit.building.name} {contract.unit.unit_number}"

        # 根据新的字段含义，租户名称应该从company或user获取，而不是party_b
        tenant_name = "未知"
        if contract.company:
            tenant_name = contract.company.company_name
        elif contract.user:
            tenant_name = _get_user_real_name(contract.user)

        contracts.append({
            'id': contract.contract_id,
            'contractNumber': contract.contract_number,
            'tenantName': tenant_name,
            'assetName': asset_name,
            'startDate': contract.start_date.strftime('%Y-%m-%d'),
            'endDate': contract.end_date.strftime('%Y-%m-%d'),
            'status': contract.status,
        })

    return Response({
        'code': 200,
        'message': '获取合同列表成功',
        'data': {
            'total': paginator.count,
            'list': contracts
        }
    })


@api_view(['GET'])
def contract_detail(request, pk):
    """
    获取单个合同详情
    """
    try:
        contract = Contract.objects.select_related(
            'unit__building', 'unit__floor', 'company', 'user'
        ).get(pk=pk)
    except Contract.DoesNotExist:
        return Response({'code': 404, 'message': '合同不存在'}, status=status.HTTP_404_NOT_FOUND)

    attachments = []
    if contract.attachment_urls:
        try:
            loaded_attachments = json.loads(contract.attachment_urls)
            if isinstance(loaded_attachments, list):
                if all(isinstance(item, str) for item in loaded_attachments):
                    attachments = [{'name': url.split('/')[-1], 'url': url} for url in loaded_attachments]
                else:
                    attachments = loaded_attachments
        except json.JSONDecodeError:
            attachments = []

    # 根据新的字段含义:
    # - party_b 字段表示"甲方主体"（出租方/园区）
    # - company_id/user_id 字段表示"乙方"（承租方/企业或个人）
    
    # 甲方为合同中记录的 party_b（园区管理方）
    party_a = contract.party_b
    
    # 乙方根据 company_id 或 user_id 动态获取（租户）
    party_b = "未知"
    if contract.company:
        party_b = contract.company.company_name
    elif contract.user:
        party_b = _get_user_real_name(contract.user)

    data = {
        'id': contract.contract_id,
        'contractNumber': contract.contract_number,
        'contractName': contract.contract_name,
        'contractType': contract.contract_type,
        'partyA': party_a,
        'partyB': party_b,
        'contractAmount': str(contract.contract_amount),
        'paymentCycle': contract.payment_cycle,
        'startDate': contract.start_date.strftime('%Y-%m-%d'),
        'endDate': contract.end_date.strftime('%Y-%m-%d'),
        'signDate': contract.sign_date.strftime('%Y-%m-%d') if contract.sign_date else None,
        'status': contract.status,
        'attachments': attachments,
        'remarks': contract.remarks
    }

    return Response({'code': 200, 'message': '获取合同详情成功', 'data': data})


# ===================================================================
# Dashboard / Tickets Statistics
# ===================================================================

@api_view(['GET'])
@permission_classes([AllowAny])
def get_pending_ticket_count(request):
    """
    获取所有待处理的服务工单总数
    """
    # 定义各类服务的"待处理"状态
    pending_statuses = {
        'repair': ['待处理', '处理中'],
        'leasing': ['待审核', '审核中'],
        'decoration': ['待审核', '审核中'],
        'water': ['待受理', '配送中'],
        'cleaning': ['待受理', '已受理'],
    }

    # 计算各类服务的待处理数量
    repair_count = RepairService.objects.filter(status__in=pending_statuses['repair']).count()
    leasing_prop_count = LeasingApplicationService.objects.filter(status__in=pending_statuses['leasing']).count()
    leasing_park_count = ParkingSpaceLeasingService.objects.filter(status__in=pending_statuses['leasing']).count()
    decoration_count = DecorationApplication.objects.filter(status__in=pending_statuses['decoration']).count()
    water_count = WaterDeliveryService.objects.filter(status__in=pending_statuses['water']).count()
    cleaning_count = CleaningBookingService.objects.filter(status__in=pending_statuses['cleaning']).count()

    # 汇总
    total_pending = repair_count + leasing_prop_count + leasing_park_count + decoration_count + water_count + cleaning_count

    return Response({
        'code': 200,
        'message': '获取待处理工单总数成功',
        'data': {
            'count': total_pending
        }
    })


@api_view(['GET'])
@permission_classes([AllowAny])
def get_ticket_type_stats(request):
    """
    获取各类型工单的统计数据，用于图表展示
    """
    # 修改返回格式为对象，而不是数组，以匹配前端期望的格式
    stats_data = {
        'repair': RepairService.objects.count(),
        'cleaning': CleaningBookingService.objects.count(),
        'water': WaterDeliveryService.objects.count(),
        'leasing': LeasingApplicationService.objects.count() + ParkingSpaceLeasingService.objects.count(),
        'decoration': DecorationApplication.objects.count(),
        'visitor': VisitorAppointmentService.objects.count(),
    }

    return Response({
        'code': 200,
        'message': '获取工单类型统计成功',
        'data': stats_data
    })


@api_view(['GET'])
@permission_classes([AllowAny])
def get_latest_tickets(request):
    """
    获取最新工单列表 (综合物业报修、保洁、送水)
    """
    limit = int(request.query_params.get('limit', 5))
    user_prefetch = ['applicant_user__companyemployeeprofile', 'applicant_user__parkemployeeprofile']

    # 从不同服务模型中获取最新的记录
    repairs = RepairService.objects.select_related('applicant_user').prefetch_related(*user_prefetch).order_by(
        '-application_time')[:limit]
    cleanings = CleaningBookingService.objects.select_related('applicant_user', 'unit').prefetch_related(
        *user_prefetch).order_by('-application_time')[:limit]
    water_deliveries = WaterDeliveryService.objects.select_related('applicant_user').prefetch_related(
        *user_prefetch).order_by('-application_time')[:limit]

    combined_list = []

    # 规范化数据格式
    for repair in repairs:
        description = (repair.fault_description[:30] + '...') if len(
            repair.fault_description) > 30 else repair.fault_description
        combined_list.append({
            'id': f'repair-{repair.repair_id}',
            'type': '物业报修',
            'description': description,
            'applicant': _get_user_real_name(repair.applicant_user),
            'time': repair.application_time,
            'status': repair.status,
        })

    for cleaning in cleanings:
        unit_desc = f"{cleaning.unit.unit_number} " if cleaning.unit else ""
        combined_list.append({
            'id': f'clean-{cleaning.booking_id}',
            'type': '保洁预约',
            'description': f"{unit_desc}预约于 {cleaning.expected_service_date.strftime('%Y-%m-%d')}",
            'applicant': _get_user_real_name(cleaning.applicant_user),
            'time': cleaning.application_time,
            'status': cleaning.status,
        })

    for water in water_deliveries:
        combined_list.append({
            'id': f'water-{water.service_id}',
            'type': '送水服务',
            'description': f"{water.delivery_address} - {water.product_name} x{water.quantity}",
            'applicant': _get_user_real_name(water.applicant_user),
            'time': water.application_time,
            'status': water.status,
        })

    # 按时间统一排序并截取最终数量
    combined_list.sort(key=lambda x: x['time'], reverse=True)
    latest_tickets = combined_list[:limit]

    # 格式化时间
    for ticket in latest_tickets:
        ticket['time'] = ticket['time'].strftime('%Y-%m-%d %H:%M:%S')

    return Response({
        'code': 200,
        'message': '获取最新工单成功',
        'data': latest_tickets
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_task_stats(request):
    """
    获取当前用户的工单统计数据
    """
    user = request.user

    try:
        # 获取用户类型
        user_type = 'user'
        employee_type = None

        # 尝试获取园区员工类型
        try:
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            user_type = 'park_employee'
            employee_type = park_employee.employee_type
        except ParkEmployeeProfile.DoesNotExist:
            pass

        # 初始化统计数据
        stats = {
            'total': 0,
            'pending': 0,
            'processing': 0,
            'completed': 0,
            'priority': {
                'high': 0,
                'medium': 0,
                'low': 0
            }
        }

        # 查询用户相关的维修工单
        repair_orders = RepairService.objects.filter(
            Q(applicant_user_id=user.user_id) | Q(handler_user_id=user.user_id)
        )

        # 查询用户相关的保洁工单
        cleaning_orders = CleaningBookingService.objects.filter(
            Q(applicant_user_id=user.user_id) | Q(handler_user_id=user.user_id)
        )

        # 查询用户相关的送水工单
        water_orders = WaterDeliveryService.objects.filter(
            Q(applicant_user_id=user.user_id) | Q(deliverer_user_id=user.user_id)
        )

        # 计算总数
        stats['total'] = repair_orders.count() + cleaning_orders.count() + water_orders.count()

        # 待处理工单
        stats['pending'] = (
                repair_orders.filter(status='待受理').count() +
                cleaning_orders.filter(status='待受理').count() +
                water_orders.filter(status='待受理').count()
        )

        # 处理中工单
        stats['processing'] = (
                repair_orders.filter(status__in=['已受理', '处理中']).count() +
                cleaning_orders.filter(status__in=['已受理', '服务中']).count() +
                water_orders.filter(status__in=['已确认备货中', '配送中']).count()
        )

        # 已完成工单
        stats['completed'] = (
                repair_orders.filter(status__in=['已完成', '已评价']).count() +
                cleaning_orders.filter(status__in=['已完成', '已评价']).count() +
                water_orders.filter(status__in=['已送达', '已评价']).count()
        )

        # 计算各优先级工单数量
        # 只计算未完成的工单（待处理和处理中）
        active_repair_orders = repair_orders.filter(status__in=['待受理', '已受理', '处理中'])
        active_cleaning_orders = cleaning_orders.filter(status__in=['待受理', '已受理', '服务中'])
        active_water_orders = water_orders.filter(status__in=['待受理', '已确认备货中', '配送中'])

        # 遍历工单计算优先级
        for order in active_repair_orders:
            priority = determine_task_priority(order)
            stats['priority'][priority] += 1

        for order in active_cleaning_orders:
            priority = determine_task_priority(order)
            stats['priority'][priority] += 1

        for order in active_water_orders:
            priority = determine_task_priority(order)
            stats['priority'][priority] += 1

        return Response({
            'code': 200,
            'data': stats
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取工单统计数据失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def update_repair_status(request, pk):
    """
    更新维修工单状态
    """
    try:
        repair_order = RepairService.objects.get(repair_id=pk)
        new_status = request.data.get('status')

        if not new_status:
            return Response({
                'code': 400,
                'message': '状态不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证状态变更是否合法
        valid_statuses = ['待受理', '已受理', '处理中', '已完成', '已评价', '已取消']
        if new_status not in valid_statuses:
            return Response({
                'code': 400,
                'message': f'无效的状态值，有效值为: {", ".join(valid_statuses)}'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 更新状态
        repair_order.status = new_status

        # 如果是接受任务，设置处理人
        if new_status == '已受理' and not repair_order.handler_user_id:
            repair_order.handler_user_id = request.user.user_id

        # 如果是完成任务，设置完成时间
        if new_status == '已完成' and not repair_order.completion_time:
            from datetime import datetime
            repair_order.completion_time = datetime.now()

        repair_order.save()

        return Response({
            'code': 200,
            'message': '工单状态更新成功',
            'data': {
                'id': repair_order.repair_id,
                'status': repair_order.status
            }
        })

    except RepairService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '维修工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'更新工单状态失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def update_cleaning_status(request, pk):
    """
    更新保洁工单状态
    """
    try:
        cleaning_order = CleaningBookingService.objects.get(booking_id=pk)
        new_status = request.data.get('status')

        if not new_status:
            return Response({
                'code': 400,
                'message': '状态不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证状态变更是否合法
        valid_statuses = ['待受理', '已受理', '服务中', '已完成', '已评价', '已取消']
        if new_status not in valid_statuses:
            return Response({
                'code': 400,
                'message': f'无效的状态值，有效值为: {", ".join(valid_statuses)}'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 更新状态
        cleaning_order.status = new_status

        # 如果是接受任务，设置处理人
        if new_status == '已受理' and not cleaning_order.handler_user_id:
            cleaning_order.handler_user_id = request.user.user_id

        # 如果是完成任务，设置完成时间
        if new_status == '已完成' and not cleaning_order.completion_time:
            from datetime import datetime
            cleaning_order.completion_time = datetime.now()

        cleaning_order.save()

        return Response({
            'code': 200,
            'message': '工单状态更新成功',
            'data': {
                'id': cleaning_order.booking_id,
                'status': cleaning_order.status
            }
        })

    except CleaningBookingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '保洁工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'更新工单状态失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def update_water_status(request, pk):
    """
    更新送水工单状态
    """
    try:
        water_order = WaterDeliveryService.objects.get(service_id=pk)
        new_status = request.data.get('status')

        if not new_status:
            return Response({
                'code': 400,
                'message': '状态不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证状态变更是否合法
        valid_statuses = ['待受理', '已确认备货中', '配送中', '已送达', '已评价', '已取消']
        if new_status not in valid_statuses:
            return Response({
                'code': 400,
                'message': f'无效的状态值，有效值为: {", ".join(valid_statuses)}'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 更新状态
        water_order.status = new_status

        # 如果是接受任务，设置配送员
        if new_status == '已确认备货中' and not water_order.deliverer_user_id:
            water_order.deliverer_user_id = request.user.user_id

        # 如果是完成任务，设置送达时间
        if new_status == '已送达' and not water_order.actual_delivery_time:
            from datetime import datetime
            water_order.actual_delivery_time = datetime.now()

        water_order.save()

        return Response({
            'code': 200,
            'message': '工单状态更新成功',
            'data': {
                'id': water_order.service_id,
                'status': water_order.status
            }
        })

    except WaterDeliveryService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '送水工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'更新工单状态失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_repair_detail(request, pk):
    """
    获取维修工单详情
    """
    try:
        repair_order = RepairService.objects.select_related('applicant_user').get(repair_id=pk)

        # 计算优先级
        priority = determine_task_priority(repair_order)

        # 获取申请人信息
        contact_name = ''
        contact_phone = ''
        if repair_order.applicant_user:
            contact_name = _get_user_real_name(repair_order.applicant_user)
            contact_phone = repair_order.applicant_user.phone or ''

        # 构建响应数据
        data = {
            'id': repair_order.repair_id,
            'type': 'repair',
            'fault_description': repair_order.fault_description,
            'media_urls': repair_order.media_urls,
            'expected_time': repair_order.expected_time.strftime(
                '%Y-%m-%d %H:%M:%S') if repair_order.expected_time else None,
            'application_time': repair_order.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': repair_order.status,
            'priority': priority,  # 添加优先级字段
            'completion_time': repair_order.completion_time.strftime(
                '%Y-%m-%d %H:%M:%S') if repair_order.completion_time else None,
            'repair_result': repair_order.repair_result,
            'repair_cost': float(repair_order.repair_cost) if repair_order.repair_cost else None,
            'rating': repair_order.rating,
            'review_content': repair_order.review_content,
            'applicant_user_id': repair_order.applicant_user_id,
            'handler_user_id': repair_order.handler_user_id,
            'unit_id': repair_order.unit_id,
            'device_id': repair_order.device_id,
            'contact_name': contact_name,  # 添加联系人姓名
            'contact_phone': contact_phone,  # 添加联系电话
        }

        # 如果有关联的单元，添加单元信息
        if repair_order.unit:
            data['unit'] = {
                'unit_id': repair_order.unit.unit_id,
                'unit_number': repair_order.unit.unit_number,
                'building_id': repair_order.unit.building_id,
                'floor_id': repair_order.unit.floor_id,
            }

        # 如果有关联的设备，添加设备信息
        if repair_order.device:
            data['device'] = {
                'device_id': repair_order.device.device_id,
                'device_name': repair_order.device.device_name,
                'device_number': repair_order.device.device_number,
                'device_type': repair_order.device.device_type,
            }

        return Response({
            'code': 200,
            'data': data
        })

    except RepairService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '维修工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取维修工单详情失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_cleaning_detail(request, pk):
    """
    获取保洁工单详情
    """
    try:
        cleaning_order = CleaningBookingService.objects.select_related('applicant_user').get(booking_id=pk)

        # 计算优先级
        priority = determine_task_priority(cleaning_order)

        # 获取申请人信息
        contact_name = ''
        contact_phone = ''
        if cleaning_order.applicant_user:
            contact_name = _get_user_real_name(cleaning_order.applicant_user)
            contact_phone = cleaning_order.applicant_user.phone or ''

        # 构建响应数据
        data = {
            'id': cleaning_order.booking_id,
            'type': 'cleaning',
            'expected_service_date': cleaning_order.expected_service_date.strftime('%Y-%m-%d'),
            'expected_time_slot': cleaning_order.expected_time_slot,
            'special_requirements': cleaning_order.special_requirements,
            'application_time': cleaning_order.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': cleaning_order.status,
            'priority': priority,  # 添加优先级字段
            'completion_time': cleaning_order.completion_time.strftime(
                '%Y-%m-%d %H:%M:%S') if cleaning_order.completion_time else None,
            'service_fee': float(cleaning_order.service_fee) if cleaning_order.service_fee else None,
            'rating': cleaning_order.rating,
            'review_content': cleaning_order.review_content,
            'applicant_user_id': cleaning_order.applicant_user_id,
            'handler_user_id': cleaning_order.handler_user_id,
            'unit_id': cleaning_order.unit_id,
            'contact_name': contact_name,  # 添加联系人姓名
            'contact_phone': contact_phone,  # 添加联系电话
        }

        # 如果有关联的单元，添加单元信息
        if cleaning_order.unit:
            data['unit'] = {
                'unit_id': cleaning_order.unit.unit_id,
                'unit_number': cleaning_order.unit.unit_number,
                'building_id': cleaning_order.unit.building_id,
                'floor_id': cleaning_order.unit.floor_id,
            }

        return Response({
            'code': 200,
            'data': data
        })

    except CleaningBookingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '保洁工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取保洁工单详情失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_water_detail(request, pk):
    """
    获取送水工单详情
    """
    try:
        water_order = WaterDeliveryService.objects.select_related('applicant_user').get(service_id=pk)

        # 计算优先级
        priority = determine_task_priority(water_order)

        # 获取申请人信息
        contact_name = ''
        contact_phone = ''
        if water_order.applicant_user:
            contact_name = _get_user_real_name(water_order.applicant_user)
            contact_phone = water_order.applicant_user.phone or ''
        else:
            # 如果没有申请用户，使用订单中的联系信息
            contact_name = water_order.contact_name
            contact_phone = water_order.contact_phone

        # 构建响应数据
        data = {
            'id': water_order.service_id,
            'type': 'water',
            'product_name': water_order.product_name,
            'quantity': water_order.quantity,
            'unit_price': float(water_order.unit_price),
            'total_amount': float(water_order.total_amount),
            'expected_delivery_time': water_order.expected_delivery_time.strftime('%Y-%m-%d %H:%M:%S'),
            'delivery_address': water_order.delivery_address,
            'contact_name': contact_name,  # 使用获取的联系人姓名
            'contact_phone': contact_phone,  # 使用获取的联系电话
            'application_time': water_order.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': water_order.status,
            'priority': priority,  # 添加优先级字段
            'actual_delivery_time': water_order.actual_delivery_time.strftime(
                '%Y-%m-%d %H:%M:%S') if water_order.actual_delivery_time else None,
            'rating': water_order.rating,
            'review_content': water_order.review_content,
            'applicant_user_id': water_order.applicant_user_id,
            'deliverer_user_id': water_order.deliverer_user_id,
            'unit_id': water_order.unit_id,
        }

        # 如果有关联的单元，添加单元信息
        if water_order.unit:
            data['unit'] = {
                'unit_id': water_order.unit.unit_id,
                'unit_number': water_order.unit.unit_number,
                'building_id': water_order.unit.building_id,
                'floor_id': water_order.unit.floor_id,
            }

        return Response({
            'code': 200,
            'data': data
        })

    except WaterDeliveryService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '送水工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取送水工单详情失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_repair_record(request, pk):
    """
    添加维修工单处理记录
    """
    try:
        repair_order = RepairService.objects.get(repair_id=pk)
        content = request.data.get('content')

        if not content:
            return Response({
                'code': 400,
                'message': '处理记录内容不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 在实际应用中，这里应该创建一个处理记录对象
        # 由于数据库中可能没有专门的记录表，这里只是模拟添加记录
        # 实际项目中应该有一个专门的处理记录表

        return Response({
            'code': 200,
            'message': '处理记录添加成功',
            'data': {
                'id': pk,
                'content': content,
                'created_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'user_id': request.user.user_id
            }
        })

    except RepairService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '维修工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'添加处理记录失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_cleaning_record(request, pk):
    """
    添加保洁工单处理记录
    """
    try:
        cleaning_order = CleaningBookingService.objects.get(booking_id=pk)
        content = request.data.get('content')

        if not content:
            return Response({
                'code': 400,
                'message': '处理记录内容不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 在实际应用中，这里应该创建一个处理记录对象

        return Response({
            'code': 200,
            'message': '处理记录添加成功',
            'data': {
                'id': pk,
                'content': content,
                'created_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'user_id': request.user.user_id
            }
        })

    except CleaningBookingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '保洁工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'添加处理记录失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_water_record(request, pk):
    """
    添加送水工单处理记录
    """
    try:
        water_order = WaterDeliveryService.objects.get(service_id=pk)
        content = request.data.get('content')

        if not content:
            return Response({
                'code': 400,
                'message': '处理记录内容不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 在实际应用中，这里应该创建一个处理记录对象

        return Response({
            'code': 200,
            'message': '处理记录添加成功',
            'data': {
                'id': pk,
                'content': content,
                'created_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'user_id': request.user.user_id
            }
        })

    except WaterDeliveryService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '送水工单不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'添加处理记录失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 员工工作台相关API
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_staff_todo_tasks(request):
    """
    获取当前登录员工的待办任务列表
    """
    try:
        user = request.user

        # 获取该员工的工单类型
        try:
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            employee_type = park_employee.employee_type
        except ParkEmployeeProfile.DoesNotExist:
            return Response({
                'code': 400,
                'message': '当前用户不是园区员工'
            }, status=status.HTTP_400_BAD_REQUEST)

        tasks = []

        # 根据员工类型获取不同的待办任务
        if employee_type in ['送水工', '配送员']:
            # 送水工获取其已接单但未完成的送水工单
            water_tasks = WaterDeliveryService.objects.filter(
                deliverer_user=user,
                status__in=['已确认备货中', '配送中']
            ).order_by('expected_delivery_time')

            for task in water_tasks:
                priority = determine_task_priority(task)
                tasks.append({
                    'id': task.service_id,
                    'type': 'water',
                    'expected_delivery_time': task.expected_delivery_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'content': f"{task.product_name} x {task.quantity}",
                    'address': task.delivery_address,
                    'priority': priority,
                    'contact_name': task.contact_name,
                    'contact_phone': task.contact_phone,
                    'status': task.status,
                    'total_amount': float(task.total_amount) if task.total_amount else 0  # 添加订单总金额
                })

        elif employee_type in ['保洁工']:
            # 保洁工获取其已接单但未完成的保洁工单
            cleaning_tasks = CleaningBookingService.objects.filter(
                handler_user=user,
                status__in=['已受理', '服务中']
            ).order_by('expected_service_date', 'expected_time_slot')

            for task in cleaning_tasks:
                priority = determine_task_priority(task)
                unit_address = ""
                if task.unit:
                    unit_address = f"{task.unit.building.name} {task.unit.floor.actual_label} {task.unit.unit_number}"
                
                # 获取申请人信息
                contact_name = ''
                contact_phone = ''
                if task.applicant_user:
                    contact_name = _get_user_real_name(task.applicant_user)
                    contact_phone = task.applicant_user.phone or ''

                tasks.append({
                    'id': task.booking_id,
                    'type': 'cleaning',
                    'expected_service_date': task.expected_service_date.strftime('%Y-%m-%d'),
                    'expected_time_slot': task.expected_time_slot,
                    'special_requirements': task.special_requirements or '无特殊要求',
                    'content': f"保洁服务 - {task.special_requirements or '无特殊要求'}",
                    'address': unit_address,
                    'priority': priority,
                    'status': task.status,
                    'contact_name': contact_name,
                    'contact_phone': contact_phone,
                    'application_time': task.application_time.strftime('%Y-%m-%d %H:%M:%S')
                })

        elif employee_type in ['维修工']:
            # 维修工获取其已接单但未完成的维修工单
            repair_tasks = RepairService.objects.filter(
                handler_user=user,
                status__in=['已受理', '处理中']
            ).order_by('expected_time')

            for task in repair_tasks:
                priority = determine_task_priority(task)
                location = _get_repair_location(task)
                
                # 获取申请人信息
                applicant = User.objects.filter(user_id=task.applicant_user_id).first()
                contact_name = ''
                contact_phone = ''
                
                if applicant:
                    contact_name = _get_user_real_name(applicant)
                    contact_phone = applicant.phone or ''

                tasks.append({
                    'id': task.repair_id,
                    'type': 'repair',
                    'expected_delivery_time': task.expected_time.strftime(
                        '%Y-%m-%d %H:%M:%S') if task.expected_time else '尽快处理',
                    'content': task.fault_description[:50] + ('...' if len(task.fault_description) > 50 else ''),
                    'address': location,
                    'priority': priority,
                    'status': task.status,
                    'contact_name': contact_name,
                    'contact_phone': contact_phone
                })

        # 将优先级转换为中文
        priority_map = {'high': '高', 'medium': '中', 'low': '低'}
        for task in tasks:
            task['priority'] = priority_map.get(task['priority'], '低')

        return Response({
            'code': 200,
            'message': '获取待办任务成功',
            'data': tasks
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取待办任务失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_staff_available_tasks(request):
    """
    获取当前登录员工可接单的任务列表
    """
    try:
        user = request.user
        
        # 记录当前时区信息
        current_tz = timezone.get_current_timezone()
        print(f"当前时区: {current_tz}, 当前时间: {timezone.now()}")

        # 获取该员工的工单类型
        try:
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            employee_type = park_employee.employee_type
            print(f"员工类型: {employee_type}")
        except ParkEmployeeProfile.DoesNotExist:
            return Response({
                'code': 400,
                'message': '当前用户不是园区员工'
            }, status=status.HTTP_400_BAD_REQUEST)

        tasks = []

        # 过滤参数
        priority_filter = request.query_params.get('priority', '')

        # 根据员工类型获取不同的可接单任务
        if employee_type in ['送水工', '配送员']:
            # 送水工获取待受理的送水工单
            water_tasks = WaterDeliveryService.objects.filter(
                status='待受理'
            ).exclude(
                deliverer_user=user  # 排除已经被该员工接单的任务
            ).order_by('expected_delivery_time')

            for task in water_tasks:
                priority = determine_task_priority(task)

                # 如果有优先级过滤，则跳过不匹配的任务
                if priority_filter and priority_filter != priority:
                    continue

                tasks.append({
                    'id': task.service_id,
                    'type': 'water',
                    'expected_delivery_time': task.expected_delivery_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'content': f"{task.product_name} x {task.quantity}",
                    'address': task.delivery_address,
                    'priority': priority,
                    'contact_name': task.contact_name,
                    'contact_phone': task.contact_phone,
                    'status': task.status
                })

        elif employee_type in ['保洁工']:
            # 保洁工获取待受理的保洁工单
            cleaning_tasks = CleaningBookingService.objects.filter(
                status='待受理'
            ).order_by('expected_service_date', 'expected_time_slot')

            for task in cleaning_tasks:
                priority = determine_task_priority(task)

                # 如果有优先级过滤，则跳过不匹配的任务
                if priority_filter and priority_filter != priority:
                    continue

                unit_address = ""
                if task.unit:
                    unit_address = f"{task.unit.building.name} {task.unit.floor.actual_label} {task.unit.unit_number}"

                # 获取申请人信息
                contact_name = ''
                contact_phone = ''
                if task.applicant_user:
                    contact_name = _get_user_real_name(task.applicant_user)
                    contact_phone = task.applicant_user.phone or ''

                tasks.append({
                    'id': task.booking_id,
                    'type': 'cleaning',
                    'expected_service_date': task.expected_service_date.strftime('%Y-%m-%d'),
                    'expected_time_slot': task.expected_time_slot,
                    'special_requirements': task.special_requirements or '无特殊要求',
                    'content': f"保洁服务 - {task.special_requirements or '无特殊要求'}",
                    'address': unit_address,
                    'priority': priority,
                    'status': task.status,
                    'application_time': task.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'contact_name': contact_name,
                    'contact_phone': contact_phone
                })

        elif employee_type in ['维修工']:
            # 维修工获取待受理的维修工单
            repair_tasks = RepairService.objects.filter(
                status='待受理'
            ).order_by('expected_time')

            for task in repair_tasks:
                priority = determine_task_priority(task)

                # 如果有优先级过滤，则跳过不匹配的任务
                if priority_filter and priority_filter != priority:
                    continue

                location = _get_repair_location(task)
                
                # 获取申请人信息
                applicant = User.objects.filter(user_id=task.applicant_user_id).first()
                contact_name = ''
                contact_phone = ''
                
                if applicant:
                    contact_name = _get_user_real_name(applicant)
                    contact_phone = applicant.phone or ''

                tasks.append({
                    'id': task.repair_id,
                    'type': 'repair',
                    'expected_delivery_time': task.expected_time.strftime(
                        '%Y-%m-%d %H:%M:%S') if task.expected_time else '尽快处理',
                    'content': task.fault_description[:50] + ('...' if len(task.fault_description) > 50 else ''),
                    'address': location,
                    'priority': priority,
                    'status': task.status,
                    'application_time': task.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'contact_name': contact_name,
                    'contact_phone': contact_phone,
                    'fault_description': task.fault_description
                })

        # 将优先级转换为中文
        priority_map = {'high': '高', 'medium': '中', 'low': '低'}
        for task in tasks:
            task['priority'] = priority_map.get(task['priority'], '低')

        return Response({
            'code': 200,
            'message': '获取可接单任务成功',
            'data': tasks
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取可接单任务失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_staff_completed_tasks(request):
    """
    获取当前登录员工已完成的任务列表
    """
    try:
        user = request.user

        # 获取该员工的工单类型
        try:
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            employee_type = park_employee.employee_type
        except ParkEmployeeProfile.DoesNotExist:
            return Response({
                'code': 400,
                'message': '当前用户不是园区员工'
            }, status=status.HTTP_400_BAD_REQUEST)

        tasks = []

        # 根据员工类型获取不同的已完成任务
        if employee_type in ['送水工', '配送员']:
            # 送水工获取其已完成的送水工单
            water_tasks = WaterDeliveryService.objects.filter(
                deliverer_user=user,
                status__in=['已送达', '已评价']
            ).order_by('-actual_delivery_time')[:20]  # 最近20条记录

            for task in water_tasks:
                completed_time = task.actual_delivery_time.strftime(
                    '%Y-%m-%d %H:%M:%S') if task.actual_delivery_time else ''
                
                # 获取申请人的联系信息
                contact_name = ""
                contact_phone = ""
                if task.applicant_user:
                    contact_name = _get_user_real_name(task.applicant_user)
                    contact_phone = task.applicant_user.phone or ""
                else:
                    # 如果没有申请用户，使用订单中的联系信息
                    contact_name = task.contact_name or ""
                    contact_phone = task.contact_phone or ""
                
                tasks.append({
                    'id': task.service_id,
                    'type': 'water',
                    'completed_time': completed_time,
                    'content': f"{task.product_name} x {task.quantity}",
                    'address': task.delivery_address,
                    'rating': task.rating or 0,
                    'status': task.status,
                    'contact_name': contact_name,
                    'contact_phone': contact_phone
                })

        elif employee_type in ['保洁工']:
            # 保洁工获取其已完成的保洁工单
            cleaning_tasks = CleaningBookingService.objects.filter(
                handler_user=user,
                status__in=['已完成', '已评价']
            ).order_by('-completion_time')[:20]  # 最近20条记录

            for task in cleaning_tasks:
                completed_time = task.completion_time.strftime('%Y-%m-%d %H:%M:%S') if task.completion_time else ''
                unit_address = ""
                if task.unit:
                    unit_address = f"{task.unit.building.name} {task.unit.floor.actual_label} {task.unit.unit_number}"

                # 获取申请人的联系信息
                contact_name = ""
                contact_phone = ""
                if task.applicant_user:
                    contact_name = _get_user_real_name(task.applicant_user)
                    contact_phone = task.applicant_user.phone or ""

                tasks.append({
                    'id': task.booking_id,
                    'type': 'cleaning',
                    'completed_time': completed_time,
                    'expected_service_date': task.expected_service_date.strftime('%Y-%m-%d') if task.expected_service_date else '',
                    'expected_time_slot': task.expected_time_slot or '',
                    'content': f"保洁服务 - {task.special_requirements or '无特殊要求'}",
                    'address': unit_address,
                    'rating': task.rating or 0,
                    'status': task.status,
                    'contact_name': contact_name,
                    'contact_phone': contact_phone
                })

        elif employee_type in ['维修工']:
            # 维修工获取其已完成的维修工单
            repair_tasks = RepairService.objects.filter(
                handler_user=user,
                status__in=['已完成', '已评价']
            ).order_by('-completion_time')[:20]  # 最近20条记录

            for task in repair_tasks:
                completed_time = task.completion_time.strftime('%Y-%m-%d %H:%M:%S') if task.completion_time else ''
                location = _get_repair_location(task)
                
                # 获取申请人的联系信息
                contact_name = ""
                contact_phone = ""
                if task.applicant_user:
                    contact_name = _get_user_real_name(task.applicant_user)
                    contact_phone = task.applicant_user.phone or ""

                tasks.append({
                    'id': task.repair_id,
                    'type': 'repair',
                    'completed_time': completed_time,
                    'content': task.fault_description[:50] + ('...' if len(task.fault_description) > 50 else ''),
                    'address': location,
                    'rating': task.rating or 0,
                    'status': task.status,
                    'contact_name': contact_name,
                    'contact_phone': contact_phone
                })

        return Response({
            'code': 200,
            'message': '获取已完成任务成功',
            'data': tasks
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取已完成任务失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_staff_performance(request):
    """
    获取员工业绩数据
    """
    try:
        user = request.user
        period = request.query_params.get('period', 'today')  # 默认为今日数据

        # 获取该员工的工单类型
        try:
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            employee_type = park_employee.employee_type
        except ParkEmployeeProfile.DoesNotExist:
            return Response({
                'code': 400,
                'message': '当前用户不是园区员工'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 根据员工类型和统计周期获取业绩数据
        now = timezone.now()
        today_start = timezone.make_aware(datetime.combine(now.date(), datetime.min.time()))

        if period == 'today':
            time_range_start = today_start
        else:  # month
            # 获取本月第一天
            month_start = datetime(now.year, now.month, 1)
            time_range_start = timezone.make_aware(month_start)

        completedOrders = 0
        acceptedOrders = 0
        totalIncome = 0
        totalRating = 0
        ratingCount = 0

        # 根据员工类型获取不同的业绩数据
        if employee_type in ['送水工', '配送员']:
            # 已完成订单数量
            completed_tasks = WaterDeliveryService.objects.filter(
                deliverer_user=user,
                status__in=['已送达', '已评价'],
                actual_delivery_time__gte=time_range_start
            )
            completedOrders = completed_tasks.count()

            # 已接单但未完成的订单数量
            acceptedOrders = WaterDeliveryService.objects.filter(
                deliverer_user=user,
                status__in=['已确认备货中', '配送中']
            ).count()

            # 总收入
            for task in completed_tasks:
                totalIncome += task.total_amount

            # 平均评分
            rated_tasks = completed_tasks.exclude(rating=None).exclude(rating=0)
            for task in rated_tasks:
                totalRating += task.rating
                ratingCount += 1

        elif employee_type in ['保洁工']:
            # 已完成订单数量
            completed_tasks = CleaningBookingService.objects.filter(
                handler_user=user,
                status__in=['已完成', '已评价'],
                completion_time__gte=time_range_start
            )
            completedOrders = completed_tasks.count()

            # 已接单但未完成的订单数量
            acceptedOrders = CleaningBookingService.objects.filter(
                handler_user=user,
                status__in=['已受理', '服务中']
            ).count()

            # 总收入
            for task in completed_tasks:
                if task.service_fee:
                    totalIncome += task.service_fee

            # 平均评分
            rated_tasks = completed_tasks.exclude(rating=None).exclude(rating=0)
            for task in rated_tasks:
                totalRating += task.rating
                ratingCount += 1

        elif employee_type in ['维修工']:
            # 已完成订单数量
            completed_tasks = RepairService.objects.filter(
                handler_user=user,
                status__in=['已完成', '已评价'],
                completion_time__gte=time_range_start
            )
            completedOrders = completed_tasks.count()

            # 已接单但未完成的订单数量
            acceptedOrders = RepairService.objects.filter(
                handler_user=user,
                status__in=['已受理', '处理中']
            ).count()

            # 总收入 - 维修可能没有直接收入
            # 暂时忽略

            # 平均评分
            rated_tasks = completed_tasks.exclude(rating=None).exclude(rating=0)
            for task in rated_tasks:
                totalRating += task.rating
                ratingCount += 1

        # 计算平均评分
        averageRating = round(totalRating / ratingCount, 1) if ratingCount > 0 else 0

        performance_data = {
            'completedOrders': completedOrders,
            'acceptedOrders': acceptedOrders,
            'totalIncome': float(totalIncome),
            'averageRating': averageRating
        }

        return Response({
            'code': 200,
            'message': '获取业绩数据成功',
            'data': performance_data
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取业绩数据失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_staff_task_distribution(request):
    """
    获取任务状态分布数据
    """
    try:
        user = request.user

        # 获取该员工的工单类型
        try:
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            employee_type = park_employee.employee_type
        except ParkEmployeeProfile.DoesNotExist:
            return Response({
                'code': 400,
                'message': '当前用户不是园区员工'
            }, status=status.HTTP_400_BAD_REQUEST)

        now = timezone.now()
        today_start = timezone.make_aware(datetime.combine(now.date(), datetime.min.time()))

        distribution = {
            'todo': 0,  # 待办任务
            'available': 0,  # 可接单任务
            'completed': 0,  # 今日已完成
            'rated': 0  # 已评价
        }

        # 根据员工类型获取不同的任务分布
        if employee_type in ['送水工', '配送员']:
            # 待办任务
            distribution['todo'] = WaterDeliveryService.objects.filter(
                deliverer_user=user,
                status__in=['已确认备货中', '配送中']
            ).count()

            # 可接单任务
            distribution['available'] = WaterDeliveryService.objects.filter(
                status='待受理'
            ).count()

            # 今日已完成
            distribution['completed'] = WaterDeliveryService.objects.filter(
                deliverer_user=user,
                status='已送达',
                actual_delivery_time__gte=today_start
            ).count()

            # 已评价
            distribution['rated'] = WaterDeliveryService.objects.filter(
                deliverer_user=user,
                status='已评价'
            ).count()

        elif employee_type in ['保洁工']:
            # 待办任务
            distribution['todo'] = CleaningBookingService.objects.filter(
                handler_user=user,
                status__in=['已受理', '服务中']
            ).count()

            # 可接单任务
            distribution['available'] = CleaningBookingService.objects.filter(
                status='待受理'
            ).count()

            # 今日已完成
            distribution['completed'] = CleaningBookingService.objects.filter(
                handler_user=user,
                status='已完成',
                completion_time__gte=today_start
            ).count()

            # 已评价
            distribution['rated'] = CleaningBookingService.objects.filter(
                handler_user=user,
                status='已评价'
            ).count()

        elif employee_type in ['维修工']:
            # 待办任务
            distribution['todo'] = RepairService.objects.filter(
                handler_user=user,
                status__in=['已受理', '处理中']
            ).count()

            # 可接单任务
            distribution['available'] = RepairService.objects.filter(
                status='待受理'
            ).count()

            # 今日已完成
            distribution['completed'] = RepairService.objects.filter(
                handler_user=user,
                status='已完成',
                completion_time__gte=today_start
            ).count()

            # 已评价
            distribution['rated'] = RepairService.objects.filter(
                handler_user=user,
                status='已评价'
            ).count()

        return Response({
            'code': 200,
            'message': '获取任务分布数据成功',
            'data': [
                {'value': distribution['todo'], 'name': '待办任务'},
                {'value': distribution['available'], 'name': '可接单任务'},
                {'value': distribution['completed'], 'name': '今日已完成'},
                {'value': distribution['rated'], 'name': '已评价'}
            ]
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取任务分布数据失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_staff_weekly_stats(request):
    """
    获取最近7天工单完成数量统计
    """
    try:
        user = request.user

        # 获取该员工的工单类型
        try:
            park_employee = ParkEmployeeProfile.objects.get(user=user)
            employee_type = park_employee.employee_type
        except ParkEmployeeProfile.DoesNotExist:
            return Response({
                'code': 400,
                'message': '当前用户不是园区员工'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 计算最近7天的日期
        today = timezone.now().date()
        date_list = [(today - timedelta(days=i)) for i in range(6, -1, -1)]
        weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        data = [0] * 7

        # 根据员工类型获取不同的统计数据
        if employee_type in ['送水工', '配送员']:
            for i, date in enumerate(date_list):
                start_time = timezone.make_aware(datetime.combine(date, datetime.min.time()))
                end_time = timezone.make_aware(datetime.combine(date, datetime.max.time()))

                count = WaterDeliveryService.objects.filter(
                    deliverer_user=user,
                    status__in=['已送达', '已评价'],
                    actual_delivery_time__range=(start_time, end_time)
                ).count()

                data[i] = count

        elif employee_type in ['保洁工']:
            for i, date in enumerate(date_list):
                start_time = timezone.make_aware(datetime.combine(date, datetime.min.time()))
                end_time = timezone.make_aware(datetime.combine(date, datetime.max.time()))

                count = CleaningBookingService.objects.filter(
                    handler_user=user,
                    status__in=['已完成', '已评价'],
                    completion_time__range=(start_time, end_time)
                ).count()

                data[i] = count

        elif employee_type in ['维修工']:
            for i, date in enumerate(date_list):
                start_time = timezone.make_aware(datetime.combine(date, datetime.min.time()))
                end_time = timezone.make_aware(datetime.combine(date, datetime.max.time()))

                count = RepairService.objects.filter(
                    handler_user=user,
                    status__in=['已完成', '已评价'],
                    completion_time__range=(start_time, end_time)
                ).count()

                data[i] = count

        # 将日期转换为星期几
        labels = [f"{date.strftime('%m-%d')} {weekdays[date.weekday()]}" for date in date_list]

        return Response({
            'code': 200,
            'message': '获取每周统计数据成功',
            'data': {
                'labels': labels,
                'values': data
            }
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取每周统计数据失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 获取当前用户的保洁预约列表
@api_view(['GET'])
def current_user_cleaning_booking_list(request):
    """
    获取当前登录用户的保洁预约服务列表
    """
    if not request.user.is_authenticated:
        return Response({
            'code': 401,
            'message': '用户未登录',
        }, status=status.HTTP_401_UNAUTHORIZED)

    params = request.query_params
    page = int(params.get('current', 1))
    size = int(params.get('size', 10))
    status_filter = params.get('status')

    queryset = CleaningBookingService.objects.select_related(
        'applicant_user', 'handler_user', 'unit__building', 'unit__floor'
    ).prefetch_related(
        'applicant_user__companyemployeeprofile',
        'applicant_user__parkemployeeprofile',
        'handler_user__parkemployeeprofile'
    ).filter(applicant_user=request.user).order_by('-application_time')

    if status_filter:
        queryset = queryset.filter(status=status_filter)

    paginator = Paginator(queryset, size)
    page_obj = paginator.get_page(page)

    booking_list = []
    for booking in page_obj.object_list:
        booking_list.append({
            'booking_id': booking.booking_id,
            'applicant_user_info': {
                'name': _get_user_real_name(booking.applicant_user)} if booking.applicant_user else None,
            'unit_info': f"{booking.unit.building.name} {booking.unit.floor.actual_label} {booking.unit.unit_number}" if booking.unit else 'N/A',
            'expected_service_date': booking.expected_service_date.strftime('%Y-%m-%d'),
            'expected_time_slot': booking.expected_time_slot,
            'application_time': booking.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': booking.status,
            'handler_user_info': {'name': _get_user_real_name(booking.handler_user)} if booking.handler_user else None,
        })

    return Response({
        'code': 200,
        'message': '获取当前用户保洁预约列表成功',
        'data': {
            'total': paginator.count,
            'list': booking_list
        }
    })


# 获取当前用户的送水服务列表
@api_view(['GET'])
def current_user_water_delivery_list(request):
    """
    获取当前登录用户的送水服务列表
    """
    if not request.user.is_authenticated:
        return Response({
            'code': 401,
            'message': '用户未登录',
        }, status=status.HTTP_401_UNAUTHORIZED)

    try:
        params = request.query_params
        page = int(params.get('current', 1))
        size = int(params.get('size', 10))
        status_filter = params.get('status')

        queryset = WaterDeliveryService.objects.filter(applicant_user=request.user).order_by('-application_time')

        # 处理多状态查询
        if status_filter:
            if ',' in status_filter:
                status_list = status_filter.split(',')
                queryset = queryset.filter(status__in=status_list)
            else:
                queryset = queryset.filter(status=status_filter)

        paginator = Paginator(queryset, size)
        page_obj = paginator.get_page(page)

        delivery_list = []
        for delivery in page_obj.object_list:
            # 使用安全的方式获取属性，避免属性不存在导致的错误
            delivery_dict = {
                'service_id': delivery.service_id,
                'product_name': delivery.product_name,
                'quantity': delivery.quantity,
                'unit_price': str(delivery.unit_price),
                'total_amount': str(delivery.total_amount),
                'expected_delivery_time': delivery.expected_delivery_time.strftime(
                    '%Y-%m-%d %H:%M:%S') if delivery.expected_delivery_time else '',
                'delivery_address': delivery.delivery_address if hasattr(delivery, 'delivery_address') else '',
                'contact_name': delivery.contact_name if hasattr(delivery, 'contact_name') else '',
                'contact_phone': delivery.contact_phone if hasattr(delivery, 'contact_phone') else '',
                'application_time': delivery.application_time.strftime(
                    '%Y-%m-%d %H:%M:%S') if delivery.application_time else '',
                'status': delivery.status,
                'applicant_user_info': {
                    'name': _get_user_real_name(delivery.applicant_user)} if delivery.applicant_user else None,
            }

            # 安全地添加处理人信息
            if hasattr(delivery, 'deliverer_user') and delivery.deliverer_user:
                delivery_dict['handler_user_info'] = {'name': _get_user_real_name(delivery.deliverer_user)}
            else:
                delivery_dict['handler_user_info'] = None

            delivery_list.append(delivery_dict)

        return Response({
            'code': 200,
            'message': '获取当前用户送水服务列表成功',
            'data': {
                'total': paginator.count,
                'list': delivery_list
            }
        })
    except Exception as e:
        # 添加错误日志记录
        print(f"Error in current_user_water_delivery_list: {str(e)}")
        return Response({
            'code': 500,
            'message': f'获取送水服务列表失败: {str(e)}',
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 创建送水服务
@csrf_exempt
def create_water_delivery(request):
    """
    创建新的送水服务订单
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.body)

            # 获取或验证Unit实例
            try:
                unit_instance = Unit.objects.get(unit_id=int(data['unit_id']))
            except Unit.DoesNotExist:
                return JsonResponse({
                    'code': 400,
                    'message': '指定的单元不存在'
                }, status=400)
            except (ValueError, KeyError):
                return JsonResponse({
                    'code': 400,
                    'message': '无效的单元ID格式'
                }, status=400)

            # 获取用户实例
            try:
                # 从请求中获取当前用户
                user_instance = request.user
                if not user_instance or not user_instance.is_authenticated:
                    return JsonResponse({
                        'code': 401,
                        'message': '用户未登录'
                    }, status=401)
            except Exception as e:
                return JsonResponse({
                    'code': 400,
                    'message': f'获取用户信息失败: {str(e)}'
                }, status=400)

            # 验证必填字段
            required_fields = ['product_name', 'quantity', 'unit_price', 'total_amount', 'expected_delivery_time',
                               'contact_name', 'contact_phone']
            missing_fields = [field for field in required_fields if field not in data or not data[field]]
            if missing_fields:
                return JsonResponse({
                    'code': 400,
                    'message': f'缺少必填字段: {", ".join(missing_fields)}'
                }, status=400)

            # 创建记录
            now = datetime.now()

            # 处理日期时间
            try:
                expected_delivery_time = datetime.strptime(data['expected_delivery_time'], '%Y-%m-%dT%H:%M:%S')
            except ValueError:
                try:
                    expected_delivery_time = datetime.strptime(data['expected_delivery_time'], '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    return JsonResponse({
                        'code': 400,
                        'message': '无效的日期时间格式'
                    }, status=400)

            # 创建送水服务记录
            water_delivery = WaterDeliveryService(
                unit=unit_instance,
                applicant_user=user_instance,
                product_name=data['product_name'],
                quantity=int(data['quantity']),
                unit_price=Decimal(data['unit_price']),
                total_amount=Decimal(data['total_amount']),
                expected_delivery_time=expected_delivery_time,
                delivery_address=data.get('delivery_address', ''),
                contact_name=data['contact_name'],
                contact_phone=data['contact_phone'],
                application_time=now,
                status='待受理',
                created_at=now,
                updated_at=now
            )
            water_delivery.save()

            return JsonResponse({
                'code': 201,
                'message': '送水服务申请成功',
                'data': {
                    'service_id': water_delivery.service_id
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'创建送水服务失败: {str(e)}'
            }, status=500)

    return JsonResponse({
        'code': 405,
        'message': '方法不被允许'
    }, status=405)


# 创建装修备案申请
@api_view(['POST'])
def create_decoration_application(request):
    """
    创建新的装修备案申请
    """
    try:
        # 验证用户是否登录
        if not request.user.is_authenticated:
            return Response({
                'code': 401,
                'message': '用户未登录',
            }, status=status.HTTP_401_UNAUTHORIZED)

        data = request.data

        # 验证必填字段
        required_fields = ['unit_id', 'construction_company', 'estimated_duration']
        missing_fields = [field for field in required_fields if field not in data or not data[field]]
        if missing_fields:
            return Response({
                'code': 400,
                'message': f'缺少必填字段: {", ".join(missing_fields)}'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 获取或验证Unit实例
        try:
            unit_instance = Unit.objects.get(unit_id=int(data['unit_id']))
        except Unit.DoesNotExist:
            return Response({
                'code': 400,
                'message': '指定的单元不存在'
            }, status=status.HTTP_400_BAD_REQUEST)
        except (ValueError, KeyError):
            return Response({
                'code': 400,
                'message': '无效的单元ID格式'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 处理设计方案URL (可能是JSON字符串或列表)
        design_plan_url = data.get('design_plan_url')
        if isinstance(design_plan_url, list):
            design_plan_url = json.dumps(design_plan_url)

        # 处理施工人员信息 (可能是JSON字符串或列表)
        construction_staff_info = data.get('construction_staff_info')
        if isinstance(construction_staff_info, list):
            construction_staff_info = json.dumps(construction_staff_info)

        # 创建记录
        now = datetime.now()

        decoration_application = DecorationApplication(
            applicant_user=request.user,
            unit=unit_instance,
            application_date=now.date(),
            design_plan_url=design_plan_url,
            construction_company=data['construction_company'],
            construction_staff_info=construction_staff_info,
            estimated_duration=int(data['estimated_duration']),
            status='待审核',
            created_at=now,
            updated_at=now
        )
        decoration_application.save()

        return Response({
            'code': 201,
            'message': '装修备案申请提交成功',
            'data': {
                'application_id': decoration_application.application_id
            }
        }, status=status.HTTP_201_CREATED)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'创建装修备案申请失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 获取当前用户的装修备案列表
@api_view(['GET'])
def current_user_decoration_applications(request):
    """
    获取当前登录用户的装修备案列表
    """
    if not request.user.is_authenticated:
        return Response({
            'code': 401,
            'message': '用户未登录',
        }, status=status.HTTP_401_UNAUTHORIZED)

    try:
        params = request.query_params
        page = int(params.get('current', 1))
        size = int(params.get('size', 10))
        status_filter = params.get('status')

        queryset = DecorationApplication.objects.select_related(
            'unit__building', 'unit__floor'
        ).filter(applicant_user=request.user).order_by('-application_date')

        if status_filter:
            queryset = queryset.filter(status=status_filter)

        paginator = Paginator(queryset, size)
        page_obj = paginator.get_page(page)

        application_list = []
        for app in page_obj.object_list:
            # 使用安全的方式获取属性，避免属性不存在导致的错误
            app_dict = {
                'application_id': app.application_id,
                'unit_info': f"{app.unit.building.name} {app.unit.floor.actual_label} {app.unit.unit_number}" if app.unit else 'N/A',
                'construction_company': app.construction_company,
                'application_date': app.application_date.strftime('%Y-%m-%d') if app.application_date else '',
                'estimated_duration': app.estimated_duration,
                'status': app.status,
                'approval_opinion': app.approval_opinion if app.approval_opinion else ''
            }

            application_list.append(app_dict)

        return Response({
            'code': 200,
            'message': '获取当前用户装修备案列表成功',
            'data': {
                'total': paginator.count,
                'list': application_list
            }
        })
    except Exception as e:
        # 添加错误日志记录
        print(f"Error in current_user_decoration_applications: {str(e)}")
        return Response({
            'code': 500,
            'message': f'获取装修备案列表失败: {str(e)}',
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 获取设备维保记录列表
@api_view(['GET'])
def device_maintenance_list(request):
    """
    获取设备维保记录列表
    """
    params = request.query_params
    page = int(params.get('page', 1))
    size = int(params.get('pageSize', 10))
    device_id = params.get('device_id')
    maintenance_type = params.get('maintenance_type')
    start_date = params.get('start_date')
    end_date = params.get('end_date')

    queryset = DeviceMaintenance.objects.select_related(
        'device', 'repair_service'
    ).order_by('-maintenance_date')

    # 筛选条件
    if device_id:
        queryset = queryset.filter(device_id=device_id)

    if maintenance_type:
        queryset = queryset.filter(maintenance_type=maintenance_type)

    if start_date:
        queryset = queryset.filter(maintenance_date__gte=start_date)

    if end_date:
        queryset = queryset.filter(maintenance_date__lte=end_date)

    paginator = Paginator(queryset, size)
    page_obj = paginator.get_page(page)

    maintenance_list = []
    for record in page_obj.object_list:
        maintenance_list.append({
            'maintenance_id': record.maintenance_id,
            'device_info': {
                'device_id': record.device.device_id,
                'device_name': record.device.device_name,
                'device_number': record.device.device_number,
                'device_type': record.device.device_type
            },
            'maintenance_type': record.maintenance_type,
            'content': record.content,
            'responsible_person': record.responsible_person,
            'maintenance_date': record.maintenance_date.strftime('%Y-%m-%d'),
            'cost': str(record.cost) if record.cost else None,
            'repair_service_id': record.repair_service.repair_id if record.repair_service else None
        })

    return Response({
        'code': 200,
        'message': '获取设备维保记录列表成功',
        'data': {
            'total': paginator.count,
            'list': maintenance_list
        }
    })


# 获取设备维保记录详情
@api_view(['GET'])
def device_maintenance_detail(request, pk):
    """
    获取设备维保记录详情
    """
    try:
        record = DeviceMaintenance.objects.select_related(
            'device', 'repair_service'
        ).get(maintenance_id=pk)
    except DeviceMaintenance.DoesNotExist:
        return Response({'code': 404, 'message': '维保记录不存在'}, status=status.HTTP_404_NOT_FOUND)

    # 获取设备详细信息
    device = record.device
    device_info = {
        'device_id': device.device_id,
        'device_name': device.device_name,
        'device_number': device.device_number,
        'device_type': device.device_type,
        'location_desc': device.location_desc,
        'brand_model': device.brand_model,
        'purchase_date': device.purchase_date.strftime('%Y-%m-%d') if device.purchase_date else None,
        'warranty_end_date': device.warranty_end_date.strftime('%Y-%m-%d') if device.warranty_end_date else None,
        'status': device.status
    }

    # 获取关联的报修信息（如果有）
    repair_info = None
    if record.repair_service:
        repair = record.repair_service
        repair_info = {
            'repair_id': repair.repair_id,
            'fault_description': repair.fault_description,
            'application_time': repair.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': repair.status,
            'completion_time': repair.completion_time.strftime('%Y-%m-%d %H:%M:%S') if repair.completion_time else None,
            'repair_result': repair.repair_result
        }

    data = {
        'maintenance_id': record.maintenance_id,
        'device_info': device_info,
        'maintenance_type': record.maintenance_type,
        'content': record.content,
        'responsible_person': record.responsible_person,
        'maintenance_date': record.maintenance_date.strftime('%Y-%m-%d'),
        'cost': str(record.cost) if record.cost else None,
        'repair_info': repair_info,
        'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        'updated_at': record.updated_at.strftime('%Y-%m-%d %H:%M:%S')
    }

    return Response({'code': 200, 'message': '获取维保记录详情成功', 'data': data})


# 创建设备维保记录
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_device_maintenance(request):
    """
    创建新的设备维保记录，同时创建关联的报修服务
    """
    try:
        data = request.data

        # 检查是否包含repairService和maintenanceRecord两部分数据
        if 'repairService' in data and 'maintenanceRecord' in data:
            repair_data = data['repairService']
            maintenance_data = data['maintenanceRecord']

            # 验证报修服务必填字段
            repair_required_fields = ['device_id', 'fault_description', 'expected_time']
            repair_missing_fields = [field for field in repair_required_fields if field not in repair_data]
            if repair_missing_fields:
                return Response({
                    'code': 400,
                    'message': f'报修服务缺少必填字段: {", ".join(repair_missing_fields)}'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 验证维保记录必填字段
            maintenance_required_fields = ['device_id', 'content']
            maintenance_missing_fields = [field for field in maintenance_required_fields if
                                          field not in maintenance_data]
            if maintenance_missing_fields:
                return Response({
                    'code': 400,
                    'message': f'维保记录缺少必填字段: {", ".join(maintenance_missing_fields)}'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 验证设备是否存在
            try:
                device = Device.objects.get(device_id=maintenance_data['device_id'])
            except Device.DoesNotExist:
                return Response({
                    'code': 400,
                    'message': '指定的设备不存在'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 创建报修服务记录
            now = datetime.now()
            repair_service = RepairService(
                applicant_user=request.user,
                device=device,
                fault_description=repair_data['fault_description'],
                status=repair_data.get('repair_status', '待处理'),
                expected_time=parse_date(repair_data['expected_time']),
                media_urls=repair_data.get('media_urls', '[]'),
                application_time=now,
                created_at=now,
                updated_at=now
            )
            repair_service.save()

            # 创建维保记录 - 维保类型固定为"维修"
            # 由于maintenance_date在数据库中是必填字段，这里使用期望维修时间作为临时占位
            # 实际的维保日期会由管理员在后续操作中更新
            expected_date = parse_date(repair_data['expected_time'])
            maintenance_record = DeviceMaintenance(
                device=device,
                maintenance_type='维修',  # 固定为维修
                content=maintenance_data['content'],
                maintenance_date=expected_date,  # 临时使用期望日期作为占位
                repair_service=repair_service,  # 关联新创建的报修服务
                created_at=now,
                updated_at=now
            )
            maintenance_record.save()

            return Response({
                'code': 201,
                'message': '创建设备维保记录和报修服务成功',
                'data': {
                    'maintenance_id': maintenance_record.maintenance_id,
                    'repair_id': repair_service.repair_id
                }
            }, status=status.HTTP_201_CREATED)

        else:
            # 原有逻辑，处理单独创建维保记录的情况
            # 验证必填字段
            required_fields = ['device_id', 'content']
            missing_fields = [field for field in required_fields if field not in data]
            if missing_fields:
                return Response({
                    'code': 400,
                    'message': f'缺少必填字段: {", ".join(missing_fields)}'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 验证设备是否存在
            try:
                device = Device.objects.get(device_id=data['device_id'])
            except Device.DoesNotExist:
                return Response({
                    'code': 400,
                    'message': '指定的设备不存在'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 如果提供了报修服务ID，验证是否存在
            repair_service = None
            if 'repair_service_id' in data and data['repair_service_id']:
                try:
                    repair_service = RepairService.objects.get(repair_id=data['repair_service_id'])
                except RepairService.DoesNotExist:
                    return Response({
                        'code': 400,
                        'message': '指定的报修服务不存在'
                    }, status=status.HTTP_400_BAD_REQUEST)

            # 创建维保记录 - 维保类型固定为"维修"
            now = datetime.now()
            # 由于maintenance_date在数据库中是必填字段，如果没有提供，则使用当前日期作为临时占位
            maintenance_date = now.date()
            if 'expected_time' in data and data['expected_time']:
                maintenance_date = parse_date(data['expected_time'])

            maintenance_record = DeviceMaintenance(
                device=device,
                maintenance_type='维修',  # 固定为维修
                content=data['content'],
                maintenance_date=maintenance_date,  # 临时使用当前日期或期望日期作为占位
                repair_service=repair_service,
                created_at=now,
                updated_at=now
            )
            maintenance_record.save()

            return Response({
                'code': 201,
                'message': '创建设备维保记录成功',
                'data': {
                    'maintenance_id': maintenance_record.maintenance_id
                }
            }, status=status.HTTP_201_CREATED)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'创建设备维保记录失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 获取当前用户的设备维保记录
@api_view(['GET'])
def current_user_device_maintenance_list(request):
    """
    获取当前登录用户的设备维保记录
    """
    if not request.user.is_authenticated:
        return Response({
            'code': 401,
            'message': '用户未登录',
        }, status=status.HTTP_401_UNAUTHORIZED)

    try:
        params = request.query_params
        page = int(params.get('page', 1))
        size = int(params.get('pageSize', 10))
        maintenance_type = params.get('maintenance_type')

        # 获取与用户关联的报修服务
        user_repair_ids = RepairService.objects.filter(
            applicant_user=request.user
        ).values_list('repair_id', flat=True)

        # 获取与这些报修服务关联的维保记录
        queryset = DeviceMaintenance.objects.select_related('device').filter(
            repair_service__in=user_repair_ids
        ).order_by('-maintenance_date')

        if maintenance_type:
            queryset = queryset.filter(maintenance_type=maintenance_type)

        paginator = Paginator(queryset, size)
        page_obj = paginator.get_page(page)

        maintenance_list = []
        for record in page_obj.object_list:
            maintenance_list.append({
                'maintenance_id': record.maintenance_id,
                'device_info': {
                    'device_name': record.device.device_name,
                    'device_number': record.device.device_number,
                    'device_type': record.device.device_type
                },
                'maintenance_type': record.maintenance_type,
                'content': record.content,
                'maintenance_date': record.maintenance_date.strftime('%Y-%m-%d'),
                'responsible_person': record.responsible_person
            })

        return Response({
            'code': 200,
            'message': '获取当前用户设备维保记录成功',
            'data': {
                'total': paginator.count,
                'list': maintenance_list
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取设备维保记录失败: {str(e)}',
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def parking_application_list(request):
    """
    获取当前用户的停车申请列表或创建新的停车申请
    """
    if request.method == 'GET':
        # 获取当前用户的停车申请列表
        applications = ParkingSpaceLeasingService.objects.select_related(
            'applicant_user', 'unit', 'vehicle', 'contract'
        ).filter(applicant_user=request.user).order_by('-application_time')

        # 可选的状态筛选
        status_filter = request.query_params.get('status', None)
        if status_filter:
            applications = applications.filter(status=status_filter)

        # 构建响应数据
        results = []
        for app in applications:
            vehicle_data = None
            if app.vehicle:
                vehicle_data = {
                    'vehicle_id': app.vehicle.vehicle_id,
                    'plate_number': app.vehicle.plate_number,
                    'vehicle_type': app.vehicle.vehicle_type,
                    'brand': app.vehicle.brand,
                    'model': app.vehicle.model,
                    'color': app.vehicle.color
                }

            app_data = {
                'application_id': app.application_id,
                'application_time': app.application_time,
                'expected_start_date': app.expected_start_date,
                'expected_duration': app.expected_duration,
                'status': app.status,
                'approval_opinion': app.approval_opinion,
                'vehicle': vehicle_data,
                'contract_id': app.contract_id
            }
            results.append(app_data)

        return Response({
            'code': 200,
            'message': '获取停车申请列表成功',
            'data': {
                'results': results
            }
        })
    
    elif request.method == 'POST':
        # 处理POST请求，直接在这里实现创建停车申请的逻辑，而不是调用create_parking_application函数
        try:
            # 获取请求数据
            vehicle_id = request.data.get('vehicle_id')
            expected_start_date = request.data.get('expected_start_date')
            expected_duration = request.data.get('expected_duration')
            remarks = request.data.get('remarks', '')

            # 验证必要字段
            if not vehicle_id or not expected_start_date or not expected_duration:
                return Response({
                    'code': 400,
                    'message': '缺少必要参数'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 验证车辆是否存在且属于当前用户
            try:
                from assets.models import Vehicle
                vehicle = Vehicle.objects.get(vehicle_id=vehicle_id)
                
                # 验证车辆所有权
                if vehicle.user_id != request.user.user_id:
                    return Response({
                        'code': 403,
                        'message': '该车辆不属于您，无法提交申请'
                    }, status=status.HTTP_403_FORBIDDEN)
            except Vehicle.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '未找到指定车辆'
                }, status=status.HTTP_404_NOT_FOUND)
            except Exception as e:
                return Response({
                    'code': 500,
                    'message': f'验证车辆信息失败: {str(e)}'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            # 获取指定的车位单元
            from assets.models import Unit
            try:
                # 获取请求中指定的车位ID
                unit_id = request.data.get('unit_id')
                if not unit_id:
                    return Response({
                        'code': 400,
                        'message': '请选择车位'
                    }, status=status.HTTP_400_BAD_REQUEST)
                
                # 检查车位是否存在且可用
                parking_unit = Unit.objects.filter(
                    unit_id=unit_id,
                    unit_type='parking_space', 
                    status='available'
                ).first()
                
                if not parking_unit:
                    return Response({
                        'code': 404,
                        'message': '所选车位不存在或已被占用'
                    }, status=status.HTTP_404_NOT_FOUND)
            except Exception as e:
                return Response({
                    'code': 500,
                    'message': f'查找车位失败: {str(e)}'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            # 创建停车申请
            application = ParkingSpaceLeasingService(
                applicant_user=request.user,
                unit=parking_unit,
                vehicle=vehicle,
                expected_start_date=expected_start_date,
                expected_duration=expected_duration,
                application_time=timezone.now(),
                status='pending',  # 初始状态为待审核
                approval_opinion=remarks if remarks else None,
                created_at=timezone.now(),
                updated_at=timezone.now()
            )
            application.save()

            return Response({
                'code': 201,
                'message': '停车申请创建成功',
                'data': {
                    'application_id': application.application_id
                }
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建停车申请失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_parking_application(request):
    """
    创建新的停车申请
    """
    try:
        # 获取请求数据
        vehicle_id = request.data.get('vehicle_id')
        expected_start_date = request.data.get('expected_start_date')
        expected_duration = request.data.get('expected_duration')
        remarks = request.data.get('remarks', '')

        # 验证必要字段
        if not vehicle_id or not expected_start_date or not expected_duration:
            return Response({
                'code': 400,
                'message': '缺少必要参数'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证车辆是否存在且属于当前用户
        try:
            from assets.models import Vehicle
            vehicle = Vehicle.objects.get(vehicle_id=vehicle_id)
            
            # 验证车辆所有权
            if vehicle.user_id != request.user.user_id:
                return Response({
                    'code': 403,
                    'message': '该车辆不属于您，无法提交申请'
                }, status=status.HTTP_403_FORBIDDEN)
        except Vehicle.DoesNotExist:
            return Response({
                'code': 404,
                'message': '未找到指定车辆'
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'验证车辆信息失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 查找可用的车位单元
        from assets.models import Unit
        try:
            # 假设车位类型的单元类型为'parking_space'
            parking_unit = Unit.objects.filter(unit_type='parking_space', status='available').first()
            if not parking_unit:
                return Response({
                    'code': 404,
                    'message': '当前没有可用的车位'
                }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'查找车位失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 创建停车申请
        application = ParkingSpaceLeasingService(
            applicant_user=request.user,
            unit=parking_unit,
            vehicle=vehicle,
            expected_start_date=expected_start_date,
            expected_duration=expected_duration,
            application_time=timezone.now(),
            status='pending',  # 初始状态为待审核
            approval_opinion=remarks if remarks else None,
            created_at=timezone.now(),
            updated_at=timezone.now()
        )
        application.save()

        return Response({
            'code': 201,
            'message': '停车申请创建成功',
            'data': {
                'application_id': application.application_id
            }
        }, status=status.HTTP_201_CREATED)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'创建停车申请失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def parking_application_detail(request, pk):
    """
    获取停车申请详情
    """
    try:
        # 获取申请详情
        application = ParkingSpaceLeasingService.objects.select_related(
            'applicant_user', 'unit', 'vehicle', 'contract'
        ).get(application_id=pk)

        # 验证是否为申请人或管理员
        if application.applicant_user != request.user and not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '您无权查看此申请'
            }, status=status.HTTP_403_FORBIDDEN)

        # 构建响应数据
        vehicle_data = None
        if application.vehicle:
            vehicle_data = {
                'vehicle_id': application.vehicle.vehicle_id,
                'plate_number': application.vehicle.plate_number,
                'vehicle_type': application.vehicle.vehicle_type,
                'brand': application.vehicle.brand,
                'model': application.vehicle.model,
                'color': application.vehicle.color
            }

        unit_data = None
        if application.unit:
            unit_data = {
                'unit_id': application.unit.unit_id,
                'unit_number': application.unit.unit_number,
                'unit_type': application.unit.unit_type,
                'actual_area': application.unit.actual_area,
                'status': application.unit.status
            }

        contract_data = None
        if application.contract:
            contract_data = {
                'contract_id': application.contract.contract_id,
                'contract_number': application.contract.contract_number,
                'contract_name': application.contract.contract_name,
                'start_date': application.contract.start_date,
                'end_date': application.contract.end_date,
                'contract_amount': application.contract.contract_amount,
                'status': application.contract.status
            }

        application_data = {
            'application_id': application.application_id,
            'application_time': application.application_time,
            'expected_start_date': application.expected_start_date,
            'expected_duration': application.expected_duration,
            'status': application.status,
            'approval_opinion': application.approval_opinion,
            'vehicle': vehicle_data,
            'unit': unit_data,
            'contract': contract_data
        }

        return Response({
            'code': 200,
            'message': '获取停车申请详情成功',
            'data': application_data
        })

    except ParkingSpaceLeasingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '未找到指定的停车申请'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取停车申请详情失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def cancel_parking_application(request, pk):
    """
    取消停车申请
    """
    try:
        # 获取申请
        application = ParkingSpaceLeasingService.objects.get(application_id=pk)

        # 验证是否为申请人
        if application.applicant_user != request.user:
            return Response({
                'code': 403,
                'message': '您无权取消此申请'
            }, status=status.HTTP_403_FORBIDDEN)

        # 验证申请状态是否可取消
        if application.status not in ['pending', 'initial_approved']:
            return Response({
                'code': 400,
                'message': '当前状态无法取消申请'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 更新申请状态
        application.status = 'cancelled'
        application.updated_at = timezone.now()
        application.save()

        return Response({
            'code': 200,
            'message': '停车申请已取消'
        })

    except ParkingSpaceLeasingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '未找到指定的停车申请'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'取消停车申请失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def submit_parking_contract(request, pk):
    """
    提交停车合同（初审通过后用户提交合同）
    """
    try:
        # 获取申请
        application = ParkingSpaceLeasingService.objects.get(application_id=pk)

        # 验证是否为申请人
        if application.applicant_user != request.user:
            return Response({
                'code': 403,
                'message': '您无权操作此申请'
            }, status=status.HTTP_403_FORBIDDEN)

        # 验证申请状态是否为初审通过
        if application.status != 'initial_approved':
            return Response({
                'code': 400,
                'message': '当前状态无法提交合同'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 获取合同ID
        contract_id = request.data.get('contract_id')
        if not contract_id:
            return Response({
                'code': 400,
                'message': '缺少合同ID'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证合同是否存在
        try:
            contract = Contract.objects.get(contract_id=contract_id)
        except Contract.DoesNotExist:
            return Response({
                'code': 404,
                'message': '未找到指定的合同'
            }, status=status.HTTP_404_NOT_FOUND)

        # 更新申请状态和关联合同
        application.contract = contract
        application.status = 'contract_pending'  # 更新状态为合同待审核
        application.updated_at = timezone.now()
        application.save()

        return Response({
            'code': 200,
            'message': '合同提交成功，等待最终审批'
        })

    except ParkingSpaceLeasingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '未找到指定的停车申请'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'提交合同失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdminUser])
def admin_parking_application_list(request):
    """
    管理员获取所有停车申请列表
    """
    try:
        # 获取所有停车申请
        applications = ParkingSpaceLeasingService.objects.select_related(
            'applicant_user', 'unit', 'vehicle', 'contract'
        ).order_by('-application_time')

        # 可选的状态筛选
        status_filter = request.query_params.get('status', None)
        if status_filter:
            applications = applications.filter(status=status_filter)

        # 构建响应数据
        results = []
        for app in applications:
            applicant_data = {
                'user_id': app.applicant_user.id,
                'username': app.applicant_user.username,
                'name': app.applicant_user.profile.name if hasattr(app.applicant_user, 'profile') else None,
                'phone': app.applicant_user.profile.phone if hasattr(app.applicant_user, 'profile') else None
            }

            vehicle_data = None
            if app.vehicle:
                vehicle_data = {
                    'vehicle_id': app.vehicle.vehicle_id,
                    'plate_number': app.vehicle.plate_number,
                    'vehicle_type': app.vehicle.vehicle_type,
                    'brand': app.vehicle.brand,
                    'model': app.vehicle.model
                }

            unit_data = None
            if app.unit:
                unit_data = {
                    'unit_id': app.unit.unit_id,
                    'unit_name': app.unit.unit_name,
                    'unit_type': app.unit.unit_type
                }

            contract_data = None
            if app.contract:
                contract_data = {
                    'contract_id': app.contract.contract_id,
                    'contract_number': app.contract.contract_number,
                    'contract_name': app.contract.contract_name
                }

            app_data = {
                'application_id': app.application_id,
                'application_time': app.application_time,
                'expected_start_date': app.expected_start_date,
                'expected_duration': app.expected_duration,
                'status': app.status,
                'approval_opinion': app.approval_opinion,
                'applicant': applicant_data,
                'vehicle': vehicle_data,
                'unit': unit_data,
                'contract': contract_data
            }
            results.append(app_data)

        return Response({
            'code': 200,
            'message': '获取停车申请列表成功',
            'data': {
                'results': results
            }
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取停车申请列表失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated, IsAdminUser])
def approve_parking_application(request, pk):
    """
    管理员审批停车申请
    """
    try:
        # 获取申请
        application = ParkingSpaceLeasingService.objects.get(application_id=pk)

        # 获取审批意见
        approval_opinion = request.data.get('approval_opinion', '')
        approval_type = request.data.get('approval_type', 'initial')  # 'initial' 或 'final'

        # 根据审批类型更新状态
        if approval_type == 'initial':
            # 初审通过
            if application.status != 'pending':
                return Response({
                    'code': 400,
                    'message': '当前状态无法进行初审'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            application.status = 'initial_approved'
        else:
            # 最终审批通过
            if application.status != 'contract_pending':
                return Response({
                    'code': 400,
                    'message': '当前状态无法进行最终审批'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            application.status = 'approved'

        # 更新审批意见和时间
        application.approval_opinion = approval_opinion
        application.updated_at = timezone.now()
        application.save()

        return Response({
            'code': 200,
            'message': '审批成功'
        })

    except ParkingSpaceLeasingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '未找到指定的停车申请'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'审批停车申请失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated, IsAdminUser])
def reject_parking_application(request, pk):
    """
    管理员拒绝停车申请
    """
    try:
        # 获取申请
        application = ParkingSpaceLeasingService.objects.get(application_id=pk)

        # 获取拒绝原因
        rejection_reason = request.data.get('rejection_reason', '')
        if not rejection_reason:
            return Response({
                'code': 400,
                'message': '请提供拒绝原因'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 验证申请状态是否可拒绝
        if application.status not in ['pending', 'contract_pending']:
            return Response({
                'code': 400,
                'message': '当前状态无法拒绝申请'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 更新申请状态和拒绝原因
        application.status = 'rejected'
        application.approval_opinion = rejection_reason
        application.updated_at = timezone.now()
        application.save()

        return Response({
            'code': 200,
            'message': '已拒绝此停车申请'
        })

    except ParkingSpaceLeasingService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '未找到指定的停车申请'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'拒绝停车申请失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def available_parking_spaces(request):
    """
    获取可用的车位列表
    """
    try:
        from assets.models import Unit
        
        # 查询所有可用的车位
        available_spaces = Unit.objects.filter(
            unit_type='parking_space', 
            status='available'
        ).select_related('building', 'floor')
        
        spaces_data = []
        for space in available_spaces:
            location = space.building.name
            if space.floor:
                location += f" {space.floor.actual_label}"
                
            spaces_data.append({
                'unit_id': space.unit_id,
                'unit_number': space.unit_number,
                'location': location,
                'rental_price': str(space.rental_price) if space.rental_price else None,
                'area': str(space.actual_area) if space.actual_area else None
            })
            
        return Response({
            'code': 200,
            'message': '获取可用车位成功',
            'data': spaces_data
        })
        
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取可用车位失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET', 'POST'])
def temporary_parking_list(request):
    """
    GET: 获取临时停车记录列表 (包含关联账单的支付状态)
    POST: 创建新的停车记录 (车辆入场)
    """
    if request.method == 'GET':
        params = request.query_params
        page = int(params.get('page', 1))
        limit = int(params.get('limit', 10))

        # 预加载关联数据以提升性能, 移除了'bill'
        queryset = TemporaryParkingService.objects.select_related(
            'vehicle', 'user', 'visitor'
        ).prefetch_related(
            'user__companyemployeeprofile', 'user__parkemployeeprofile'
        ).order_by('-entry_time')

        # 筛选逻辑
        if params.get('plate_number'):
            queryset = queryset.filter(plate_number__icontains=params.get('plate_number'))
        
        # 根据关联的账单状态进行筛选 (修改后)
        payment_status_filter = params.get('payment_status')
        if payment_status_filter:
            paid_bill_ids = Bill.objects.filter(payment_status='已支付').values_list('pk', flat=True)
            if payment_status_filter == '已支付':
                queryset = queryset.filter(bill_id__in=paid_bill_ids)
            elif payment_status_filter == '未支付':
                queryset = queryset.filter(Q(bill_id__isnull=True) | ~Q(bill_id__in=paid_bill_ids))

        if params.get('start_date'):
            queryset = queryset.filter(entry_time__date__gte=params.get('start_date'))
        if params.get('end_date'):
            queryset = queryset.filter(entry_time__date__lte=params.get('end_date'))

        paginator = Paginator(queryset, limit)
        page_obj = paginator.get_page(page)
        
        # 手动预加载关联的账单
        parking_records_list = list(page_obj.object_list)
        bill_ids = [record.bill_id for record in parking_records_list if record.bill_id]
        bills_dict = Bill.objects.in_bulk(bill_ids)

        records = []
        for record in parking_records_list:
            user_info = None
            if record.user:
                user_info = {'user_id': record.user.user_id, 'name': _get_user_real_name(record.user)}
            
            visitor_info = None
            if record.visitor:
                visitor_info = {'visitor_id': record.visitor.visitor_id, 'name': record.visitor.name}

            vehicle_info = None
            if record.vehicle:
                vehicle_info = {'vehicle_id': record.vehicle.vehicle_id, 'vehicle_type': record.vehicle.vehicle_type}
            
            # 从手动预加载的字典中获取支付状态和时间
            payment_status = '未支付'
            payment_time = None
            bill = bills_dict.get(record.bill_id)
            if bill:
                payment_status = bill.payment_status
                if bill.payment_date:
                    payment_time = bill.payment_date.strftime('%Y-%m-%d %H:%M:%S')

            records.append({
                'parking_record_id': record.parking_record_id,
                'plate_number': record.plate_number,
                'entry_time': record.entry_time.strftime('%Y-%m-%d %H:%M:%S') if record.entry_time else None,
                'exit_time': record.exit_time.strftime('%Y-%m-%d %H:%M:%S') if record.exit_time else None,
                'parking_duration': record.parking_duration,
                'fee_rate': str(record.fee_rate) if record.fee_rate is not None else None,
                'payable_amount': str(record.payable_amount) if record.payable_amount is not None else None,
                'payment_status': payment_status,
                'payment_time': payment_time,
                'entry_channel': record.entry_channel,
                'exit_channel': record.exit_channel,
                'user': user_info,
                'visitor': visitor_info,
                'vehicle': vehicle_info,
                'bill_id': record.bill_id,
            })
        
        return Response({
            'code': 200, 'message': 'Success', 'data': {'results': records, 'count': paginator.count}
        })

    elif request.method == 'POST':
        data = request.data
        plate_number = data.get('plate_number')

        if not plate_number:
            return Response({'code': 400, 'message': '车牌号不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        if TemporaryParkingService.objects.filter(plate_number=plate_number, exit_time__isnull=True).exists():
            return Response({'code': 400, 'message': f'车牌号 {plate_number} 的车辆已在场内，无法重复入场'}, status=status.HTTP_400_BAD_REQUEST)
        
        record = TemporaryParkingService(
            plate_number=plate_number,
            entry_time=data.get('entry_time', timezone.now()),
            entry_channel=data.get('entry_channel'),
            fee_rate=data.get('fee_rate'),
            created_at=timezone.now(),
            updated_at=timezone.now()
        )
        
        try:
            vehicle = Vehicle.objects.select_related('user', 'visitor').get(plate_number=plate_number)
            record.vehicle = vehicle
            if vehicle.user:
                record.user = vehicle.user
            elif vehicle.visitor:
                record.visitor = vehicle.visitor
        except Vehicle.DoesNotExist:
            pass  # 临时车辆，没有预先登记，是正常情况
        
        record.save()
        return Response({'code': 201, 'message': '车辆入场登记成功'}, status=status.HTTP_201_CREATED)

@transaction.atomic
@api_view(['PUT'])
def temporary_parking_detail(request, pk):
    """
    更新停车记录 (车辆出场), 并生成关联的账单
    """
    try:
        record = TemporaryParkingService.objects.select_related('user').get(pk=pk)
    except TemporaryParkingService.DoesNotExist:
        return Response({'code': 404, 'message': '停车记录不存在'}, status=status.HTTP_404_NOT_FOUND)

    if record.exit_time:
        return Response({'code': 400, 'message': '该车辆已出场，无法重复操作'}, status=status.HTTP_400_BAD_REQUEST)

    data = request.data
    exit_time_str = data.get('exit_time')
    
    if not exit_time_str:
        return Response({'code': 400, 'message': '出场时间不能为空'}, status=status.HTTP_400_BAD_REQUEST)

    try:
        # Django REST framework 自动处理了时区, 前端传来的ISO格式字符串可直接使用
        exit_time = datetime.fromisoformat(exit_time_str.replace('Z', '+00:00'))
    except ValueError:
        return Response({'code': 400, 'message': '出场时间格式不正确'}, status=status.HTTP_400_BAD_REQUEST)
    
    # 确保出场时间晚于入场时间
    if exit_time <= record.entry_time:
        return Response({'code': 400, 'message': '出场时间必须晚于入场时间'}, status=status.HTTP_400_BAD_REQUEST)

    # 计算费用
    duration_seconds = (exit_time - record.entry_time).total_seconds()
    duration_minutes = round(duration_seconds / 60)
    
    payable_amount = Decimal('0.00')
    if record.fee_rate and duration_minutes > 0:
        # 不足一小时按一小时计算
        billable_hours = (duration_minutes + 59) // 60
        payable_amount = Decimal(billable_hours) * record.fee_rate

    # 更新停车记录
    record.exit_time = exit_time
    record.exit_channel = data.get('exit_channel')
    record.parking_duration = duration_minutes
    record.payable_amount = payable_amount

    # 如果产生了费用，则创建账单
    if payable_amount > 0:
        bill_number = f"PK-{timezone.now().strftime('%Y%m%d%H%M%S')}-{record.parking_record_id}"
        
        payer_company = None
        if record.user:
            try:
                payer_company = record.user.companyemployeeprofile.company
            except CompanyEmployeeProfile.DoesNotExist:
                pass

        new_bill = Bill.objects.create(
            bill_number=bill_number,
            payer_user=record.user,
            payer_company=payer_company,
            amount=payable_amount,
            due_date=exit_time.date(),
            payment_status='未支付',
            bill_type='停车费',
            remarks=f"车牌号 {record.plate_number} 临时停车费",
            created_at=timezone.now(),
            updated_at=timezone.now()
        )
        record.bill_id = new_bill.pk
    
    record.save()
    return Response({'code': 200, 'message': '车辆出场成功，账单已生成'})


@api_view(['GET'])
def get_vehicle_by_plate(request, plate_number):
    try:
        vehicle = Vehicle.objects.select_related(
            'user', 'visitor'
        ).prefetch_related(
            'user__companyemployeeprofile', 'user__parkemployeeprofile'
        ).get(plate_number=plate_number)
        
        user_info = None
        if vehicle.user:
            user_info = {'user_id': vehicle.user.user_id, 'name': _get_user_real_name(vehicle.user)}
        
        visitor_info = None
        if vehicle.visitor:
            visitor_info = {'visitor_id': vehicle.visitor.visitor_id, 'name': vehicle.visitor.name}

        data = {
            'vehicle_id': vehicle.vehicle_id,
            'plate_number': vehicle.plate_number,
            'brand': vehicle.brand,
            'model': vehicle.model,
            'color': vehicle.color,
            'vehicle_type': vehicle.vehicle_type,
            'user': user_info,
            'visitor': visitor_info,
        }
        return Response({'code': 200, 'message': 'Success', 'data': data})
    except Vehicle.DoesNotExist:
        return Response({'code': 404, 'message': '车辆未登记'}, status=status.HTTP_404_NOT_FOUND)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_housing_detail(request, pk):
    """
    获取当前用户的房源详情
    """
    try:
        # 查找租赁申请
        try:
            application = LeasingApplicationService.objects.get(
                application_id=pk,
                applicant_user=request.user
            )
        except LeasingApplicationService.DoesNotExist:
            return Response({
                'code': 404,
                'message': '未找到指定的房源申请'
            }, status=status.HTTP_404_NOT_FOUND)

        # 获取合同信息
        contract = None
        try:
            contract = Contract.objects.filter(application=application).first()
        except:
            pass

        # 构建响应数据
        housing_data = {
            'application_id': application.application_id,
            'application_time': application.application_time.strftime('%Y-%m-%d %H:%M:%S'),
            'status': application.status,
            'remarks': application.remarks,
            'applicant_info': {
                'name': application.applicant_name,
                'phone': application.applicant_phone,
                'id_number': application.applicant_id_number,
                'company': application.applicant_company
            },
            'unit': {
                'unit_id': application.unit.unit_id,
                'unit_number': application.unit.unit_number,
                'unit_type': application.unit.unit_type,
                'actual_area': str(application.unit.actual_area) if application.unit.actual_area else '0.00',
                'building_area': str(application.unit.building_area) if application.unit.building_area else '0.00',
                'rental_price': str(application.unit.rental_price) if application.unit.rental_price else '0.00',
                'property_fee_standard': str(
                    application.unit.property_fee_standard) if application.unit.property_fee_standard else '0.00',
                'orientation': application.unit.orientation,
                'facilities_desc': application.unit.facilities_desc,
                'media_urls': application.unit.media_urls,
                'building': {
                    'building_id': application.unit.building.building_id,
                    'name': application.unit.building.name
                },
                'floor': {
                    'floor_id': application.unit.floor.floor_id if application.unit.floor else None,
                    'actual_label': application.unit.floor.actual_label if application.unit.floor else None
                } if application.unit.floor else None
            } if application.unit else None,
            'contract': {
                'contract_id': contract.contract_id,
                'contract_content': contract.contract_content,
                'contract_start_date': contract.contract_start_date.strftime(
                    '%Y-%m-%d') if contract.contract_start_date else None,
                'contract_end_date': contract.contract_end_date.strftime(
                    '%Y-%m-%d') if contract.contract_end_date else None,
                'created_at': contract.created_at.strftime('%Y-%m-%d %H:%M:%S')
            } if contract else None
        }

        return Response({
            'code': 200,
            'message': '获取房源详情成功',
            'data': housing_data
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取房源详情失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def current_user_leasing_applications(request):
    """
    获取当前用户的租赁申请列表
    """
    try:
        user = request.user
        status_filter = request.query_params.get('status')

        # 查询条件
        query = Q(applicant_user=user)
        if status_filter:
            query &= Q(status=status_filter)

        # 查询数据
        applications = LeasingApplicationService.objects.filter(query).select_related(
            'unit', 'unit__building', 'unit__floor', 'company'
        ).order_by('-application_time')

        # 分页
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        paginator = Paginator(applications, page_size)
        applications_page = paginator.get_page(page)

        # 构建响应数据
        applications_data = []
        for app in applications_page:
            applications_data.append({
                'application_id': app.application_id,
                'status': app.status,
                'application_time': app.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                'expected_start_date': app.expected_start_date.strftime('%Y-%m-%d'),
                'expected_duration': app.expected_duration,
                'approval_opinion': app.approval_opinion,
                'unit': {
                    'unit_id': app.unit.unit_id,
                    'unit_number': app.unit.unit_number,
                    'unit_type': app.unit.unit_type,
                    'actual_area': str(app.unit.actual_area) if app.unit.actual_area else '0.00',
                    'rental_price': str(app.unit.rental_price) if app.unit.rental_price else '0.00',
                    'building': app.unit.building.name if app.unit.building else '',
                    'floor': app.unit.floor.actual_label if app.unit.floor else ''
                },
                'company': {
                    'company_id': app.company.company_id,
                    'company_name': app.company.company_name
                } if app.company else None
            })

        return Response({
            'code': 200,
            'message': '获取租赁申请列表成功',
            'data': {
                'total': paginator.count,
                'page': page,
                'page_size': page_size,
                'list': applications_data
            }
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取租赁申请列表失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def cancel_leasing_application(request, pk):
    """
    取消租赁申请
    """
    try:
        # 查找租赁申请
        application = LeasingApplicationService.objects.get(application_id=pk)

        # 检查是否是申请人本人
        if application.applicant_user != request.user:
            return Response({
                'code': 403,
                'message': '您没有权限取消此申请'
            }, status=status.HTTP_403_FORBIDDEN)

        # 检查申请状态是否可以取消
        if application.status not in ['待初审', '待复审']:
            return Response({
                'code': 400,
                'message': f'当前状态({application.status})不允许取消申请'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 开始事务
        with transaction.atomic():
            # 更新申请状态
            application.status = '已取消'
            application.save()

            # 更新房源状态为空置
            if application.unit:
                application.unit.status = '空置'
                application.unit.save()

        return Response({
            'code': 200,
            'message': '租赁申请已成功取消'
        })

    except LeasingApplicationService.DoesNotExist:
        return Response({
            'code': 404,
            'message': '未找到指定的租赁申请'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'取消租赁申请失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def submit_leasing_contract(request):
    """
    提交租赁合同
    """
    try:
        data = request.data

        # 验证必填字段
        required_fields = ['application_id', 'contract_content', 'contract_start_date', 'contract_end_date']
        for field in required_fields:
            if field not in data:
                return Response({
                    'code': 400,
                    'message': f'缺少必填字段: {field}'
                }, status=status.HTTP_400_BAD_REQUEST)

        # 查找租赁申请
        application_id = data['application_id']
        try:
            application = LeasingApplicationService.objects.get(application_id=application_id)
        except LeasingApplicationService.DoesNotExist:
            return Response({
                'code': 404,
                'message': '未找到指定的租赁申请'
            }, status=status.HTTP_404_NOT_FOUND)

        # 检查是否是申请人本人
        if application.applicant_user != request.user:
            return Response({
                'code': 403,
                'message': '您没有权限提交此合同'
            }, status=status.HTTP_403_FORBIDDEN)

        # 检查申请状态是否正确
        if application.status != '初审通过':
            return Response({
                'code': 400,
                'message': f'当前状态({application.status})不允许提交合同'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 开始事务
        with transaction.atomic():
            # 创建合同
            contract = Contract.objects.create(
                application=application,
                contract_content=data['contract_content'],
                contract_start_date=data['contract_start_date'],
                contract_end_date=data['contract_end_date'],
                created_by=request.user
            )

            # 更新申请状态
            application.status = '待复审'
            application.save()

            # 更新房源状态
            if application.unit:
                application.unit.status = '待复审'
                application.unit.save()

        return Response({
            'code': 200,
            'message': '合同提交成功',
            'data': {
                'contract_id': contract.contract_id
            }
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'提交合同失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_housing(request):
    """
    获取当前用户的房源列表
    """
    try:
        # 获取当前用户的租赁申请
        applications = LeasingApplicationService.objects.filter(
            applicant_user=request.user
        ).select_related('unit', 'unit__building', 'unit__floor').order_by('-application_time')

        # 分页
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        paginator = Paginator(applications, page_size)
        applications_page = paginator.get_page(page)

        # 构建响应数据
        housing_list = []
        for app in applications_page:
            # 获取合同信息
            contract = None
            try:
                contract = Contract.objects.filter(application=app).first()
            except:
                pass

            housing_data = {
                'application_id': app.application_id,
                'application_time': app.application_time.strftime('%Y-%m-%d %H:%M:%S'),
                'status': app.status,
                'unit': {
                    'unit_id': app.unit.unit_id,
                    'unit_number': app.unit.unit_number,
                    'unit_type': app.unit.unit_type,
                    'actual_area': str(app.unit.actual_area) if app.unit.actual_area else '0.00',
                    'rental_price': str(app.unit.rental_price) if app.unit.rental_price else '0.00',
                    'building': {
                        'building_id': app.unit.building.building_id,
                        'name': app.unit.building.name
                    },
                    'floor': {
                        'floor_id': app.unit.floor.floor_id if app.unit.floor else None,
                        'actual_label': app.unit.floor.actual_label if app.unit.floor else None
                    } if app.unit.floor else None
                } if app.unit else None,
                'contract': {
                    'contract_id': contract.contract_id,
                    'contract_start_date': contract.contract_start_date.strftime(
                        '%Y-%m-%d') if contract.contract_start_date else None,
                    'contract_end_date': contract.contract_end_date.strftime(
                        '%Y-%m-%d') if contract.contract_end_date else None
                } if contract else None
            }
            housing_list.append(housing_data)

        return Response({
            'code': 200,
            'message': '获取我的房源列表成功',
            'data': {
                'total': paginator.count,
                'page': page,
                'page_size': page_size,
                'list': housing_list
            }
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取我的房源列表失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_leasing_application(request):
    """
    创建租赁申请
    """
    try:
        data = request.data
        user = request.user

        # 验证必要参数
        required_fields = ['unit_id', 'expected_start_date', 'expected_duration']
        for field in required_fields:
            if field not in data:
                return Response({
                    'code': 400,
                    'message': f'缺少必要参数: {field}'
                }, status=status.HTTP_400_BAD_REQUEST)

        # 验证单元是否存在
        try:
            unit = Unit.objects.get(pk=data['unit_id'])
        except Unit.DoesNotExist:
            return Response({
                'code': 404,
                'message': '房源不存在'
            }, status=status.HTTP_404_NOT_FOUND)

        # 验证单元是否可租赁
        if unit.status != '空置':
            return Response({
                'code': 400,
                'message': '该房源当前不可租赁'
            }, status=status.HTTP_400_BAD_REQUEST)

        # 获取企业ID（如果有）
        company_id = data.get('company_id')
        company = None
        if company_id:
            try:
                company = Company.objects.get(pk=company_id)
            except Company.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '企业不存在'
                }, status=status.HTTP_404_NOT_FOUND)

        # 创建租赁申请
        application = LeasingApplicationService.objects.create(
            applicant_user=user,
            company=company,
            unit=unit,
            expected_start_date=data['expected_start_date'],
            expected_duration=data['expected_duration'],
            application_time=timezone.now(),
            status='待初审',
            created_at=timezone.now(),
            updated_at=timezone.now())

        # 返回成功响应
        return Response({
            'code': 201,
            'message': '租赁申请提交成功',
            'data': {
                'application_id': application.application_id
            }
        }, status=status.HTTP_201_CREATED)

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'租赁申请提交失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def user_available_units(request):
    """
    获取当前登录用户可用的单元列表，用于服务预约
    """
    try:
        # 获取当前用户
        user = request.user
        print(f"当前用户ID: {user.pk}, 用户名: {user.username}")
        
        # 查询与用户相关的单元
        # 1. 查找用户通过租赁申请获得的单元
        leasing_units = Unit.objects.filter(
            leasingapplicationservice__applicant_user=user,
            leasingapplicationservice__status='已生效'  # 只考虑已生效的租赁
        ).select_related('building', 'floor').distinct()
        
        print(f"用户直接租赁单元数: {leasing_units.count()}")
        for unit in leasing_units:
            print(f"单元ID: {unit.unit_id}, 单元号: {unit.unit_number}, 楼宇: {unit.building.name if unit.building else '无'}, 楼层: {unit.floor.actual_label if unit.floor and unit.floor.actual_label else '无标签'}")
        
        # 2. 如果用户是企业员工，也查找其所属企业租用的单元
        company_units = []
        try:
            if hasattr(user, 'companyemployeeprofile') and user.companyemployeeprofile.company:
                company = user.companyemployeeprofile.company
                print(f"用户所属公司ID: {company.company_id}, 公司名称: {company.company_name}")
                company_units = Unit.objects.filter(
                    leasingapplicationservice__company=company,
                    leasingapplicationservice__status='已生效'  # 只考虑已生效的租赁
                ).select_related('building', 'floor').distinct()
                
                print(f"公司租赁单元数: {company_units.count()}")
                for unit in company_units:
                    print(f"公司单元ID: {unit.unit_id}, 单元号: {unit.unit_number}, 楼宇: {unit.building.name if unit.building else '无'}, 楼层: {unit.floor.actual_label if unit.floor and unit.floor.actual_label else '无标签'}")
        except Exception as e:
            print(f"获取企业单元时出错: {str(e)}")
        
        # 合并查询集并去重
        all_units = list(leasing_units) + list(company_units)
        unique_units = {unit.unit_id: unit for unit in all_units}.values()
        print(f"合并后去重单元数: {len(unique_units)}")
        
        # 构建响应数据
        unit_list = []
        for unit in unique_units:
            # 获取楼层标签，如果为空则使用楼层号
            floor_label = ""
            if unit.floor:
                if unit.floor.actual_label:
                    floor_label = unit.floor.actual_label
                else:
                    floor_label = f"{unit.floor.floor_number}层"
            else:
                floor_label = "1层"  # 默认值
            
            # 构建单元数据
            unit_data = {
                'unit_id': unit.unit_id,
                'unit_number': unit.unit_number,
                'building_name': unit.building.name if unit.building else "会议中心",  # 默认值
                'floor_label': floor_label,
                'unit_type': unit.unit_type,
                'actual_area': str(unit.actual_area) if unit.actual_area else '0'
            }
            print(f"添加单元数据: {unit_data}")
            unit_list.append(unit_data)
        
        # 如果没有单元，使用一个模拟数据进行测试
        if not unit_list:
            print("没有找到单元数据，使用单元42的真实数据")
            try:
                test_unit = Unit.objects.get(unit_id=42)
                unit_list.append({
                    'unit_id': test_unit.unit_id,
                    'unit_number': test_unit.unit_number,
                    'building_name': test_unit.building.name if test_unit.building else "会议中心",
                    'floor_label': test_unit.floor.actual_label if test_unit.floor and test_unit.floor.actual_label else "1层",
                    'unit_type': test_unit.unit_type,
                    'actual_area': str(test_unit.actual_area) if test_unit.actual_area else '0'
                })
                print(f"添加测试单元数据: {unit_list[0]}")
            except Exception as e:
                print(f"获取测试单元失败: {str(e)}")
        
        # 按楼宇名称和单元编号排序
        unit_list = sorted(unit_list, key=lambda x: (x['building_name'], x['unit_number']))
        
        return Response({
            'code': 200,
            'message': '获取用户单元列表成功',
            'data': unit_list
        })
    
    except Exception as e:
        print(f"API异常: {str(e)}")
        return Response({
            'code': 500,
            'message': f'获取用户单元列表失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([AllowAny])
def companies_for_visitor(request):
    """
    获取访客预约可选的企业列表
    """
    search = request.query_params.get('search', '')
    
    # 查询企业列表，支持按名称搜索
    queryset = Company.objects.all()
    
    if search:
        queryset = queryset.filter(company_name__icontains=search)
    
    # 按企业名称排序
    queryset = queryset.order_by('company_name')
    
    # 构建返回数据
    companies = []
    for company in queryset:
        companies.append({
            'company_id': company.company_id,
            'company_name': company.company_name,
            'company_type': company.company_type,
            'contact_phone': company.contact_phone
        })
    
    return Response({
        'code': 200,
        'message': '获取企业列表成功',
        'list': companies
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_visitor_appointments(request):
    """
    获取当前登录用户关联的访客预约列表
    """
    try:
        params = request.query_params
        page = int(params.get('page', 1))
        page_size = int(params.get('pageSize', 10))

        # 只获取当前用户作为邀请人的预约
        queryset = VisitorAppointmentService.objects.select_related(
            'visitor', 'visited_company', 'inviter_user'
        ).filter(
            inviter_user=request.user  # 关键筛选条件：只获取当前用户作为邀请人的预约
        ).order_by('-expected_visit_time')

        # 筛选
        if params.get('status') and params.get('status') != '':
            status_map = {'0': '待审批', '1': '已批准', '2': '已拒绝', '3': '已入园', '4': '已离园', '5': '已取消'}
            status_str = status_map.get(params.get('status'))
            if status_str:
                queryset = queryset.filter(status=status_str)

        if params.get('date'):
            date_obj = datetime.datetime.strptime(params.get('date'), '%Y-%m-%d').date()
            start_datetime = timezone.make_aware(datetime.datetime.combine(date_obj, datetime.time.min))
            end_datetime = timezone.make_aware(datetime.datetime.combine(date_obj, datetime.time.max))
            queryset = queryset.filter(expected_visit_time__range=[start_datetime, end_datetime])

        paginator = Paginator(queryset, page_size)
        page_obj = paginator.get_page(page)

        appointment_list = []
        status_map_rev = {'待审批': 0, '已批准': 1, '已拒绝': 2, '已入园': 3, '已离园': 4, '已取消': 5}

        for app in page_obj.object_list:
            appointment_list.append({
                'appointment_id': app.appointment_id,
                'visitor': {
                    'visitor_id': app.visitor.visitor_id,
                    'name': app.visitor.name,
                    'phone': app.visitor.phone,
                    'id_card': app.visitor.id_card
                },
                'visited_company': {
                    'company_id': app.visited_company.company_id,
                    'company_name': app.visited_company.company_name
                } if app.visited_company else None,
                'visit_purpose': app.visit_purpose,
                'expected_visit_time': app.expected_visit_time.isoformat(),
                'status': status_map_rev.get(app.status, -1),
                'created_at': app.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })

        return Response({
            'code': 200,
            'message': '获取我的访客预约列表成功',
            'data': {
                'total': paginator.count,
                'list': appointment_list
            }
        })

    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取我的访客预约列表失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
